Fastest way to convert a string of type id = 1 & type = 2 to an array in PHP?

I need to change it to:

$arr['id']=1;

$arr['type']=2;
+3
source share
5 answers

Usage: parse_str () .

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

Parses str, as if it is a query string passed through a URL, and sets the 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

?>
+7
source

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
)

, parse_str() . . , . , register_globals() .

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

Use parse_str()with the second argument , for example:

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

parse_str($str, $arr);

$arr will contain:

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

Source: https://habr.com/ru/post/1728403/


All Articles