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?
One way is using
print_r(array, true)
and it will return string representation of arrayIf 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 usejson_encode($value)
for a quick and simple formatted output. (note it works well on other data types too)This is the most basic version I can think of:
This is my solution for example for an div data-attributes: