Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse query string into an array

Tags:

arrays

string

php

People also ask

How to convert query string to array PHP?

Using query strings in PHP is a good way of transferring data from one file to another. This is done by using the $_GET variable. This variable is a global variable that is used to get the content of the query string and allow you to get at this data as an array.

What does parse_ str do?

The parse_str() function parses a query string into variables. Note: If the array parameter is not set, variables set by this function will overwrite existing variables of the same name. Note: The magic_quotes_gpc setting in the php. ini file affects the output of this function.


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