How to implode array with key and value without foreach in PHP How to implode array with key and value without foreach in PHP arrays arrays

How to implode array with key and value without foreach in PHP


You could use http_build_query, like this:

<?php  $a=array("item1"=>"object1", "item2"=>"object2");  echo http_build_query($a,'',', ');?>

Output:

item1=object1, item2=object2 

Demo


and another way:

$input = array(    'item1'  => 'object1',    'item2'  => 'object2',    'item-n' => 'object-n');$output = implode(', ', array_map(    function ($v, $k) {        if(is_array($v)){            return $k.'[]='.implode('&'.$k.'[]=', $v);        }else{            return $k.'='.$v;        }    },     $input,     array_keys($input)));

or:

$output = implode(', ', array_map(    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },    $input,    array_keys($input)));


I spent measurements (100000 iterations), what fastest way to glue an associative array?

Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"

We have array (for example):

$array = [    'test0' => 344,    'test1' => 235,    'test2' => 876,    ...];

Test number one:

Use http_build_query and str_replace:

str_replace('=', ':', http_build_query($array, null, ','));

Average time to implode 1000 elements: 0.00012930955084904

Test number two:

Use array_map and implode:

implode(',', array_map(        function ($v, $k) {            return $k.':'.$v;        },        $array,        array_keys($array)    ));

Average time to implode 1000 elements: 0.0004890081976675

Test number three:

Use array_walk and implode:

array_walk($array,        function (&$v, $k) {            $v = $k.':'.$v;        }    );implode(',', $array);

Average time to implode 1000 elements: 0.0003874126245348

Test number four:

Use foreach:

    $str = '';    foreach($array as $key=>$item) {        $str .= $key.':'.$item.',';    }    rtrim($str, ',');

Average time to implode 1000 elements: 0.00026632803902445

I can conclude that the best way to glue the array - use http_build_query and str_replace