Method for key value pair, similar to php explosion?

Is there an existing function in PHP for creating an associative array from a delimited string? If not, what would be the most effective way to do this? I am watching the new NVP PayPal API, where requests and responses have the following format:

method=blah&name=joe&id=joeuser&age=33&stuff=junk 

I can use explode() so that each pair explode() into the value of the array, but it would be even better if I could perform some function like dictionary_explode and specify a key separator and return an associated array, for example

 Array { [method] => blah [name] => joe [id] => joeuser [age] => 33 [stuff] => junk 

}

My CS friends tell me that this idea exists in other languages ​​like Python, so I wonder if I have found such a thing for PHP. Right now I'm looking at creating array_walk, but I would prefer something more prepared.

+4
source share
1 answer

PHP has a built-in function for it: parse_str()

 <?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 ?> 

Note. . My recommendation is not to use the first form ( parse_str($str) ) for the same reason register_globals . The second form ( parse_str($str, $arr) ) is always preferred.

+12
source

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


All Articles