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


Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

Using parse_str().

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

Solution 4:[4]

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

Solution 5:[5]

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.

Solution 6:[6]

There are several possible methods, but for you, there is already a built-in parse_str function:

$array = array();
parse_str($string, $array);
var_dump($array);

Solution 7:[7]

This is a one-liner for parsing a query from the current URL into an array:

parse_str($_SERVER['QUERY_STRING'], $query);

Solution 8:[8]

You can use the PHP string function parse_str() followed by foreach loop.

$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
  echo "$key => $value<br>";
}
print_r($my_arr);

Solution 9:[9]

You can try this code:

<?php
    $str = "pg_id=2&parent_id=2&document&video";
    $array = array();
    parse_str($str, $array);
    print_r($array);
?>

Output:

Array
(
    [pg_id] => 2
    [parent_id] => 2
    [document] =>
    [video] =>
)

Solution 10:[10]

But PHP already comes with a built in $_GET function. this will convert it to the array by itself.

try print_r($_GET) and you will get the same results.