How to explode URL parameter list string into paired [key] => [value] Array?

26,087

Solution 1

Use PHP's parse_str function.

$str = 'a=1&b=2&c=3';
$exploded = array();
parse_str($str, $exploded);
$exploded['a']; // 1

I wonder where you get this string from? If it's part of the URL after the question mark (the query string of an URL), you can already access it via the superglobal $_GET array:

# in script requested with http://example.com/script.php?a=1&b=2&c=3
$_GET['a']; // 1
var_dump($_GET); // array(3) { ['a'] => string(1) '1', ['b'] => string(1) '2', ['c'] => string(1) '3' )

Solution 2

Try to use the parse_str() function:

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
Share:
26,087
ProgrammerGirl
Author by

ProgrammerGirl

Updated on July 12, 2020

Comments

  • ProgrammerGirl
    ProgrammerGirl almost 4 years

    Possible Duplicate:
    Parse query string into an array

    How can I explode a string such as:

    a=1&b=2&c=3
    

    So that it becomes:

    Array {
     [a] => 1
     [b] => 2
     [c] => 3
    }
    

    Using the regular explode() function delimited on the & will separate the parameters but not in [key] => [value] pairs.

    Thanks.