PHP: Parse Unparse String Array
Here is a quick tip on parsing and unparsing string and array in PHP.
You can parses the string into variables by using the parse_str PHP function.
Using parse_str function
void parse_str ( string $str [, array &$arr ] )
$str = The input string.
$arr = If the second parameter arr is present, variables are stored in this variable as array elements instead.
Using single parameter
1 2 3 4 5 | $str = "first=value&arr[]=foo+bar&arr[]=baz"; parse_str($str, $data); echo $first; // value echo $arr[0]; // foo bar echo $arr[1]; // baz |
Using the second parameter
1 2 3 | $str = "first=value&arr[]=foo+bar&arr[]=baz"; parse_str($str, $data); echo "<pre>"; print_r($data); echo "</pre>"; |
The output will be:-
1 2 3 4 5 6 7 8 9 10 | Array ( [first] => value [arr] => Array ( [0] => foo bar [1] => baz ) ) |
You can unparse any array into string using the http_build_query function. This generates a URL-encoded query string from the associative (or indexed) array provided.
1 2 3 4 5 6 7 | $data = array('foo'=>'bar', 'baz'=>'boom', 'cow'=>'milk', 'php'=>'hypertext processor'); echo http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor echo http_build_query($data, '', '&'); // foo=bar&baz=boom&cow=milk&php=hypertext+processor |
Hope this helps. Thanks.





Mukesh Chapagain is a graduate of Kathmandu University (Dhulikhel, Nepal) from where he holds a Masters degree in Computer Engineering. Mukesh is a passionate web developer who has keen interest in open source technologies, programming & blogging.