135

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?

womp
  • 115,835
  • 26
  • 236
  • 269
matpie
  • 17,033
  • 9
  • 61
  • 82
  • 4
    Don't forget if you are outputting HTML, the correct syntax is & not &, iow this is wrong JOE yes it works but it's invalid HTML. – TravisO Jan 06 '09 at 18:21

11 Answers11

187

You can use http_build_query() to do that.

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

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
Greg
  • 316,276
  • 54
  • 369
  • 333
  • 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 Jan 02 '09 at 21:11
  • 2
    I wonder if this is really the fastest way for the general question. There is some encoding going on in this function. So, if it's not for a URL, is this really faster than array_walk and what if you don't want it encoded? – e-motiv Jan 31 '14 at 23:12
  • 17
    the problem is `http_build_query` escape special char – Sisyphus Feb 09 '15 at 15:42
  • 1
    I've compared serialize(), json_encode() and http_build_query(). http_build_query() won by a slight margin over serialize(), and json_encode being the slowest by far. – ErnestV Feb 24 '15 at 23:05
  • 8
    It also encodes special characters, so this is not a good option – awavi Jun 10 '15 at 21:11
  • to commenters, what if you don't need any special chars? Then this solution is perfect – OZZIE Jun 26 '18 at 13:53
46

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"}]
scunliffe
  • 62,582
  • 25
  • 126
  • 161
36

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

  • 6
    If the syntax of create_function is confusing anyone, see http://php.net/manual/en/function.create-function.php – Matt Fletcher Sep 09 '13 at 09:41
  • array_walk is slower from foreach and more complicated for read. See this: http://www.reddit.com/r/PHP/comments/1uuc34/quick_test_to_see_if_array_walk_is_better_than/ – Enyby Dec 01 '14 at 00:25
  • Found this version useful as the first solution as http_build_query() encodes URLs. – Ernesto Allely Apr 15 '16 at 14:20
22

This is my solution for example for an div data-attributes:

<?

$attributes = array(
    'data-href'   => 'http://example.com',
    'data-width'  => '300',
    'data-height' => '250',
    'data-type'   => 'cover',
);

$dataAttributes = array_map(function($value, $key) {
    return $key.'="'.$value.'"';
}, array_values($attributes), array_keys($attributes));

$dataAttributes = implode(' ', $dataAttributes);

?>

<div class="image-box" <?= $dataAttributes; ?> >
    <img src="http://example.com/images/best-of.jpg" alt="">
</div>
user4846194
  • 221
  • 2
  • 2
21

One way is using print_r(array, true) and it will return string representation of array

Raptor
  • 53,206
  • 45
  • 230
  • 366
dino.keco
  • 1,401
  • 1
  • 12
  • 18
7

My solution:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 
kostikovmu
  • 411
  • 5
  • 6
  • i liked this approach as it looks simpler than other long codes. though this is not exactly what we are after.. we look for this format : "key: value\r\n...." so i used this fomula : to get that urldecode(str_replace("=", ": ", http_build_query($headers,"", "\r\n"))). look below for this as proposed solution. – fekiri malek Feb 15 '23 at 23:24
3

What about this shorter, more transparent, yet more intuitive with array_walk

$attributes = array(
  'data-href'   => 'http://example.com',
  'data-width'  => '300',
  'data-height' => '250',
  'data-type'   => 'cover',
);

$args = "";
array_walk(
    $attributes, 
    function ($item, $key) use (&$args) {
        $args .= $key ." = '" . $item . "' ";  
    }
);
// output: 'data-href="http://example.com" data-width="300" data-height="250" data-type="cover"
FantomX1
  • 1,577
  • 2
  • 15
  • 23
2
function array_to_attributes ( $array_attributes )
{

    $attributes_str = NULL;
    foreach ( $array_attributes as $attribute => $value )
    {

        $attributes_str .= " $attribute=\"$value\" ";

    }

    return $attributes_str;
}

$attributes = array(
    'data-href'   => 'http://example.com',
    'data-width'  => '300',
    'data-height' => '250',
    'data-type'   => 'cover',
);

echo array_to_attributes($attributes) ;
Softmixt
  • 1,658
  • 20
  • 20
2

A one-liner for creating string of HTML attributes (with quotes) from a simple array:

$attrString = str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

Example:

$attrArray = array("id"    => "email", 
                   "name"  => "email",
                   "type"  => "email",
                   "class" => "active large");

echo str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

// Output:
// id="email" name="email" type="email" class="active large"
Community
  • 1
  • 1
WackGet
  • 2,667
  • 3
  • 36
  • 50
1

Use array_walk for this.

$arr = [
    "key"  => "value",
    "key2" => "value2",
];

array_walk($arr, function(&$value, $key) {
    $value = "{$key}: {$value}";
});

implode("<br/>", $arr)

Result

key: value<br/>key2: value2<br/>
Unicco
  • 2,466
  • 1
  • 26
  • 30
0

I liked the approach of @kostikovmu as it looks simpler than other long codes. though this is not exactly what we are after.. We look for this header format : "...key: value\r\n...".

So i used extended the fomula to get that

urldecode(str_replace("=", ": ", http_build_query($headers,"", "\r\n")))
fekiri malek
  • 354
  • 1
  • 3
  • 14