[php] Fastest way to implode an associative array with keys

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?

This question is related to php arrays query-string associative-array implode

The answer is


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"}]

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"

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"

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>

echo implode(",", array_keys($companies->toArray()));

$companies->toArray() -- this is just in case if your $variable is an object, otherwise just pass $companies.

That's it!


My solution:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 

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


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>

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


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

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"

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


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


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"}]

My solution:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 

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"

This is the most basic version I can think of:

public function implode_key($glue = "", $pieces = array())
{
    $keys = array_keys($pieces);
    return implode($glue, $keys);
}

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

echo implode(",", array_keys($companies->toArray()));

$companies->toArray() -- this is just in case if your $variable is an object, otherwise just pass $companies.

That's it!


This is the most basic version I can think of:

public function implode_key($glue = "", $pieces = array())
{
    $keys = array_keys($pieces);
    return implode($glue, $keys);
}

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


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to query-string

How can I get (query string) parameters from the URL in Next.js? How to read values from the querystring with ASP.NET Core? What is the difference between URL parameters and query strings? How to get URL parameter using jQuery or plain JavaScript? How to access the GET parameters after "?" in Express? node.js http 'get' request with query string parameters Escaping ampersand in URL In Go's http package, how do I get the query string on a POST request? Append values to query string Node.js: Difference between req.query[] and req.params

Examples related to associative-array

How to insert a new key value pair in array in php? Rename a dictionary key How to update specific key's value in an associative array in PHP? Is there a way to create key-value pairs in Bash script? PHP combine two associative arrays into one array Are there dictionaries in php? Display array values in PHP Adding an item to an associative array Extract subset of key-value pairs from Python dictionary object? Java associative-array

Examples related to implode

Return single column from a multi-dimensional array How to implode array with key and value without foreach in PHP php implode (101) with quotes Implode an array with JavaScript? Fastest way to implode an associative array with keys