tom91136 tom91136 - 2 years ago 125
PHP Question

php how to implode array with key and value without foreach

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
already, but it doesn't implode the key with it...

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

My solution uses nested foreach which is not what I wanted

**EDIT:**I've changed the string

This question was asked quite a while ago. At that time, I wanted to write everything in one line so I would use trinary operators and nest built in function calls in favor of foreach. That was not a good practice! Write code that is readable, whether it's concise 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 :)).

Answer Source

and another way:

$input = array(
    'item1'  => 'object1',
    'item2'  => 'object2',
    'item-n' => 'object-n'

$output = implode(', ', array_map(
    function ($v, $k) {
            return $k.'[]='.implode('&'.$k.'[]=', $v);
            return $k.'='.$v;


$output = implode(', ', array_map(
    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download