Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Without foreach, how can I turn an array like this

array("item1"=>"object1", "item2"=>"object2",......."item-n"=>"object-n");

to a string like this

item1='object1', item2='object2',.... item-n='object-n'

I thought about implode() already, but it doesn't implode the key with it.

If foreach it necessary, is it possible to not nest the foreach?

EDIT: I've changed the string


EDIT2/UPDATE: This question was asked quite a while ago. At that time, I wanted to write everything in one line so I would use ternary operators and nest built in function calls in favor of foreach. That was not a good practice! Write code that is readable, whether it is concise or not doesn't matter that much.

In this case: putting the foreach in a function will be much more readable and modular than writing a one-liner(Even though all the answers are great!).

like image 569
tom91136 Avatar asked Oct 04 '22 22:10

tom91136


2 Answers

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

like image 239
stewe Avatar answered Oct 22 '22 15:10

stewe


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)
));
like image 210
Rodrigo Crispim Avatar answered Oct 22 '22 15:10

Rodrigo Crispim