views:

67

answers:

5

I need to change it into :

$arr['id']=1;

$arr['type']=2;
+2  A: 

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
parse_str does not return a value, so that code wouldn't work right.
zipcodeman
That's much better.
zipcodeman
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
That's what php.net is for!
zipcodeman
+2  A: 

See parse_str.

outis
+7  A: 

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

?>
zipcodeman
+1  A: 
$arr = array();
$values = explode("&",$string);
foreach ($values as $value)
{
  array_push($arr,explode("=",$value));
}
Travis
A: 

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