http_build_query()
Easily build a query string from the elements of an array. This function takes care of URL-encoding, array notation, the argument separator and everything needed for a URL query string.
The first parameter is an array containing all of the values to be in the query string. For example, if “id=25″ is to appear in the resulting string, $arr['id'] would hold the value 25 if $arr is the array you’re passing to this function.
The other parameters are optional. The second parameter is a prefix string to be applied to any numeric keys of your array. This is to ensure that the resulting variable is a valid name should the query string be interpreted so on the other end.
The third parameter (as of PHP 5.1.2) allows you to specify the argument separator. If this is not set, it is taken from the arg_separator.output setting which is likely to be “&”.
$arr = array('a' => 'zebra', 'b' => 'yak', 'c' => 'Xavier', 'litmus', 'test', 'd' => 'whale'); $str1 = http_build_query($arr); // a=zebra&b=yak&c=Xavier&0=litmus&1=test&d=whale $str2 = http_build_query($arr, 'pre_'); // a=zebra&b=yak&c=Xavier&pre_0=litmus&pre_1=test&d=whale $str3 = http_build_query($arr, 'pre_', '$'); // a=zebra$b=yak$c=Xavier$pre_0=litmus$pre_1=test$d=whale $str3 = http_build_query($arr, 'pre_', 'monkey'); // a=zebramonkeyb=yakmonkeyc=Xaviermonkeypre_0=litmusmonkeypre_1=testmonkeyd=whale
As you can see, passing in the argument separator can have undesired affects. It’s best to keep to the default separator when creating URLs for the internet.
$arr = array('a' => 'zebra', 'b' => 'yak', 'c' => array('apple', 'banana', 'carrot'), array('q' => 17, 'total'), 'litmus', 'test', 'd' => 'whale'); $str = http_build_query($arr); // a=zebra&b=yak&c%5B0%5D=apple&c%5B1%5D=banana&c%5B2%5D=carrot&0%5Bq%5D=17&0%5B0%5D=total&1=litmus&2=test&d=whale /* Since the string is URL-encoded, we have %5B which is "[" and %5D which is "]" So we have ... c[0]=apple&c[1]=banana ... */
