3

I need to change it into :

$arr['id']=1;

$arr['type']=2;
1

5 Answers 5

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

?>
Sign up to request clarification or add additional context in comments.

1 Comment

This answer should have a warning for the first method, since it will overwrite variables in global scope.
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.

2 Comments

parse_str does not return a value, so that code wouldn't work right.
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? :)
2

See parse_str.

Comments

1
$arr = array();
$values = explode("&",$string);
foreach ($values as $value)
{
  array_push($arr,explode("=",$value));
}

Comments

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.