Fastest way to implode an associative array with keys
Asked Answered
D

11

136

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?

Dunlap answered 2/1, 2009 at 21:6 Comment(1)
Don't forget if you are outputting HTML, the correct syntax is &amp; not &, iow this is wrong <a href="?name=joe&age=22">JOE</a> yes it works but it's invalid HTML.Toodleoo
S
189

You can use http_build_query() to do that.

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

Shive answered 2/1, 2009 at 21:9 Comment(6)
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 uk2.php.net/manual/en/function.implode.php#84684 but http_build_query() will properly be faster.Wheelwright
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?Harmonious
the problem is http_build_query escape special charDelenadeleon
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.Materialist
It also encodes special characters, so this is not a good optionMotor
to commenters, what if you don't need any special chars? Then this solution is perfectReasoned
M
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"}]
Myrmecology answered 12/10, 2014 at 3:12 Comment(0)
S
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 :)

Semester answered 3/2, 2009 at 14:6 Comment(3)
If the syntax of create_function is confusing anyone, see php.net/manual/en/function.create-function.phpMohave
array_walk is slower from foreach and more complicated for read. See this: reddit.com/r/PHP/comments/1uuc34/…Harts
Found this version useful as the first solution as http_build_query() encodes URLs.Reprobative
P
24

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>
Periclean answered 29/4, 2015 at 11:41 Comment(0)
B
21

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

Backman answered 5/1, 2013 at 15:13 Comment(2)
$request_str=print_r($_REQUEST,true); // flatten array for log fileRosetta
But that outputs in the print_r format, not as key=value joined with a supplied separator.Ciccia
S
9

My solution:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 
Substantial answered 19/6, 2019 at 15:29 Comment(1)
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.Toweling
A
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"
Asphyxia answered 3/11, 2017 at 16:21 Comment(0)
D
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) ;
Darn answered 2/1, 2009 at 21:6 Comment(0)
Y
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"
Yves answered 27/4, 2017 at 18:30 Comment(0)
P
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/>
Predatory answered 3/3, 2022 at 11:29 Comment(0)
T
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")))
Toweling answered 15/2, 2023 at 23:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.