views:

5154

answers:

3

I'm looking for a fast way to turn an associative array in to a string. Typical structure would be like a URL query string but with customizable separators so I can use '&' for xhtml links or '&' otherwise.

My first inclination is to use foreach but since my method could be called many times in one request I fear it might be too slow.

<?php
$Amp = $IsXhtml ? '&amp;' : '&';
$Parameters = array('Action' => 'ShowList', 'Page' => '2');
$QueryString = '';
foreach ($Parameters as $Key => $Value)
        $QueryString .= $Amp . $Key . '=' . $Value;

Is there a faster way?

+14  A: 

You can use http_build_query() to do that.

Greg
Was trying to find this method in the PHP API myself this is definitely the way to go. If not the alternative is to use a modified implode method such as http://uk2.php.net/manual/en/function.implode.php#84684 but http_build_query() will properly be faster.
Mark Davidson
+3  A: 

Are you seeing a performance hit when you run this code? If you aren't, you should check this link out, and decide if it's really an issue worth burning cycles on.

Hardware is Cheap, Programmers are Expensive

bigmattyh
That code is plain ugly. The http_build_query function is certainly the right way to go with. So, @bigmattyh, not only hardware is cheap and programmers are expensive, but also slim code is sexy! ;)
Alex Polo
And, the willness to make it sexy is double sexy! :0)
Alex Polo
+1  A: 

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 Params
array_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 :)