Array to query string php – Query string to array php

Content

PHP two userful function for convert Array to query string php and Query string to array php with example.

For web development process, array to query string convert process requires in many cases and query string to array requires in some special cases like, Filter or unset GET request parameter values for temp process, without affect $_GET.

PHP
PHP

You will find both process: Array to query string php – Query string to array php with example and usage in post.

Array to query string php

If you want to convert PHP array in query string format for passing in GET request, no need to process full array.

PHP provide simple http_build_query function for generate URL-encoded query string.

Array(associative) to query string php example:

$data = array(
    'one' => 'bar',
    'two' => 'boom',
    'three' => 'milk',
    'four' => 'hypertext processor'
);

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&');

//OUTPUT
one=bar&two=boom&three=milk&four=hypertext+processor
one=bar&two=boom&three=milk&four=hypertext+processor

Array(associative, simple) to query string php example:

$data = array('one', 'two', 'three', 'four' => 'milk', 'five' => 'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myKey_');

//OUTPUT
0=one&1=bar&2=two&3=three&four=milk&five=hypertext+processor
myKey_0=one&myKey_1=two&myKey_2=three&four=milk&five=hypertext+processor

Query string to array php

If you want to convert Query string to array format for use GET request query sting parameter in process, PHP have simple and easy to use function for it.

PHP provide simple parse_str function for parses the string into variables.

$str = "paraNormal=value&paraArr[]=value1&paraArr[]=value2";
parse_str($str);
echo $paraNormal;
echo $paraArr[0];
echo $paraArr[1];

parse_str($str, $myArr);
echo $myArr['paraNormal'];
echo $myArr['paraArr'][0];
echo $myArr['paraArr'][1];