Parse query string into an array

PhpArraysString

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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 - Php

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 - Php

Using parse_str().

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

Solution 4 - Php

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 5 - Php

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 6 - Php

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 - Php

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

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

Solution 8 - Php

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 - Php

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 - Php

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.

Solution 11 - Php

This is the PHP code to split a query in MySQL and SQL Server:

function splitquery($strquery)
{
    $arrquery = explode('select', $strquery);

    $stry = ''; $strx = '';

    for($i=0; $i<count($arrquery); $i++)
    {
        if($i == 1)
        {
            echo 'select ' . trim($arrquery[$i]);
        }
        elseif($i > 1)
        {
            $strx = trim($arrquery[($i-1)]);

            if(trim(substr($strx,-1)) != '(')
            {
                $stry = $stry . '

                        select ' . trim($arrquery[$i]);
            }
            else
            {
                $stry = $stry.trim('select ' . trim($arrquery[$i]));
            }
            $strx = '';
        }
    }
    return $stry;
}

Example:

Query before

Select xx from xx select xx,(select xx) from xx where y='    cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc";

Query after

select xx from xx

select xx,(select xx) from xx where y='    cc'

select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc

Solution 12 - Php

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRunView Question on Stackoverflow
Solution 1 - PhpAnthonyView Answer on Stackoverflow
Solution 2 - Phpyassine2020View Answer on Stackoverflow
Solution 3 - PhpRocket HazmatView Answer on Stackoverflow
Solution 4 - PhpIonut BajescuView Answer on Stackoverflow
Solution 5 - PhpCasper WilkesView Answer on Stackoverflow
Solution 6 - PhpKingCrunchView Answer on Stackoverflow
Solution 7 - PhphovadoView Answer on Stackoverflow
Solution 8 - Phpuser8241064View Answer on Stackoverflow
Solution 9 - PhpYagnik SanganiView Answer on Stackoverflow
Solution 10 - PhpjerryurenaaView Answer on Stackoverflow
Solution 11 - PhpDewa PutraView Answer on Stackoverflow
Solution 12 - PhpNassimView Answer on Stackoverflow