Sunday, April 08, 2012

Simplest way to display Array Key and Values in PHP

Displaying the values of an associative array is something which you do every other day. At times you need to display both key and value of the associative array. One of the methods is to loop thru the array var and format the string by concatenating key and value. PHP provides another easy way to achieve this, infact it's a one liner solution and the solution is, use http_build_query. It takes an associative array and then convert it into query parameter. Based on default settings it uses & as a separator. What if you want to show data in the following format?


By using the following code you can achieve the desire result.

$user = array('Name'=>'Adnan',


echo http_build_query($user, '', '\n');
The third parameter is used as a separator. Make sure you don't omit the second parameter