Parse query string into an array

How can I turn a string below into an array?

pg_id=2&parent_id=2&document&video 

This is the array I am looking for,

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);

Sometimes parse_str() alone is note accurate, it could display for example:

$url = "somepage?id=123&lang=gr&size=300";

parse_str() would return:

Array ( 
    [somepage?id] => 123 
    [lang] => gr 
    [size] => 300 
)

It would be better to combine parse_str() with parse_url() like so:

$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );

Using parse_str().

$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);

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' =>
)

Use http://us1.php.net/parse_str

Attention, its usage is:

parse_str($str, &$array);

not

$array = parse_str($str);

Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4.