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 ? '&' : '&';
$Parameters = array('Action' => 'ShowList', 'Page' => '2');
$QueryString = '';
foreach ($Parameters as $Key => $Value)
$QueryString .= $Amp . $Key . '=' . $Value;
Is there a faster way?
You can use
http_build_query()
to do that.What about this shorter, more transparent, yet more intuitive with array_walk
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....
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 :)
A one-liner for creating string of HTML attributes (with quotes) from a simple array:
Example:
$companies->toArray()
-- this is just in case if your$variable
is an object, otherwise just pass $companies.That's it!