How can I turn a string below into an array?
pg_id=2&parent_id=2&document&video
This is the
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
This is one-liner for parsing query from current URL into array:
parse_str($_SERVER['QUERY_STRING'], $query);