Fastest way to implode an associative array with keys Fastest way to implode an associative array with keys arrays arrays

Fastest way to implode an associative array with keys


You can use http_build_query() to do that.

Generates a URL-encoded query string from the associative (or indexed) array provided.


If you're not concerned about the exact formatting however you do want something simple but without the line breaks of print_r you can also use json_encode($value) for a quick and simple formatted output. (note it works well on other data types too)

$str = json_encode($arr);//output...[{"id":"123","name":"Ice"},{"id":"234","name":"Cake"},{"id":"345","name":"Pie"}]


As an aside, I was in search to find the best way to implode an associative array but using my own seperators etc...

So I did this using PHP's array_walk() function to let me join an associative array into a list of parameters that could then be applied to a HTML tag....

// Create Params Array$p = Array("id"=>"blar","class"=>"myclass","onclick"=>"myJavascriptFunc()");// Join Paramsarray_walk($p, create_function('&$i,$k','$i=" $k=\"$i\"";'));$p_string = implode($p,"");// Now use $p_string for your html tag

Obviously, you could stick that in your own function somehow but it gives you an idea of how you can join an associative array using your own method.Hope that helps someone :)