PHP convert a sentence with and commercial (&) in array

Asked

Viewed 261 times

0

Has a native PHP function that converts a Querystring to Array

Example: page=index&produto=115&usuario=2

Array(
[0] => 'page=index',
[1] => 'produto=115',
[2] => 'usuario=2'
)

I know I can use explode('&' QueryString), but I remember it had a function that already identified the & as a separator for the array.

Thank you.

  • 2

    PHP does this natively when you do a GET or POST, and you can fetch the values for the keys with $_GET['page'] for example, isn’t that what you’re looking for? or else you can explain better where this querystring comes from?

1 answer

2

As @Sergio said, PHP does this automatically if it is a URL. If this is any string, you can use the function parse_str.

parse_str ( string $str [, array &$arr ] ) Converts str as if it had been passed via URL and sets the value of variables.


$str = "first=value&arr[]=foo+bar&arr[]=baz";

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

Browser other questions tagged

You are not signed in. Login or sign up in order to post.