Fastest way to implode an associative array with keys

matpie picture matpie · Jan 2, 2009 · Viewed 184.8k times · Source

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?

Answer

Greg picture Greg · Jan 2, 2009

You can use http_build_query() to do that.

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