3

I need to change it into :

$arr['id']=1;

$arr['type']=2;
user198729
  • 61,774
  • 108
  • 250
  • 348
  • Possible duplicate of [How to get parameters from this URL string?](http://stackoverflow.com/questions/11480763/how-to-get-parameters-from-this-url-string) – nhahtdh Oct 26 '15 at 05:00

5 Answers5

7

Use: parse_str().

void parse_str(string $str [, array &$arr])  

Parses str as if it were the query string passed via a URL and sets variables in the current scope.

Example:

<?php
    $str = "first=value&arr[]=foo+bar&arr[]=baz";
    parse_str($str);
    echo $first;  // value
    echo $arr[0]; // foo bar
    echo $arr[1]; // baz

    parse_str($str, $output);
    echo $output['first'];  // value
    echo $output['arr'][0]; // foo bar
    echo $output['arr'][1]; // baz

?>
zmbush
  • 2,790
  • 1
  • 17
  • 35
  • This answer should have a warning for the first method, since it will overwrite variables in global scope. – nhahtdh Oct 26 '15 at 04:59
3

Assuming you want to parse what looks like a query string, just use parse_str():

$input = 'id=1&type=2';
$out = array();
parse_str($input, $out);
print_r($out);

Output:

Array
(
    [id] => 1
    [type] => 2
)

You can optionally not pass in the second parameter and parse_str() will instead inject the variables into the current scope. Don't do this in the global scope. And I might argue don't do it at all. It's for the same reason that register_globals() is bad.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • parse_str does not return a value, so that code wouldn't work right. – zmbush Jan 14 '10 at 03:19
  • Who can remember which PHP functions mutate an array, return an array, have the array as the first parameter or the second and so on? :) – cletus Jan 14 '10 at 03:23
2

See parse_str.

outis
  • 75,655
  • 22
  • 151
  • 221
1
$arr = array();
$values = explode("&",$string);
foreach ($values as $value)
{
  array_push($arr,explode("=",$value));
}
Travis
  • 5,021
  • 2
  • 28
  • 37
0

Use parse_str() with the second argument, like this:

$str = 'id=1&type=2';

parse_str($str, $arr);

$arr will then contain:

Array
(
    [id] => 1
    [type] => 2
)
Alix Axel
  • 151,645
  • 95
  • 393
  • 500