Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

without foreach, how can i turning an array like the following

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?

my solution used nested foreach which is not what i wanted

EDIT: i've changed the string

share|improve this question
How nested foreach would be necesarry? – Shubham Jul 11 '12 at 7:14
What are you attempting? Why do you have those constraints? – Madara Uchiha Jul 11 '12 at 7:27
this was my database class for web app i'm building, i don't want it to look messy since it's already populated with a bunch of foreach and for-loop all together – Tom91136 Jul 11 '12 at 7:30
@downvoter, why downvote? – Tom91136 Jul 11 '12 at 7:38

5 Answers

up vote 4 down vote accepted

and another way:

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

http://codepad.viper-7.com/QDkjeh

or:

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

http://codepad.viper-7.com/DUPJ0y

share|improve this answer
function key_implode(&$array, $glue) {
    $result = "";

    foreach ($array as $key => $value) {
        $result .= $key . "=" . $value . $glue;
    }

    return substr($result, (-1 * strlen($glue));
}

Usage:

$str = key_implode($yourArray, ",");
share|improve this answer

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

share|improve this answer
is it possible to make the object1 into 'object1' – Tom91136 Jul 11 '12 at 7:23
Never used the other parameters of http_build_query. – shiplu.mokadd.im Jul 11 '12 at 7:38

I would use serialise() or json_encode().

While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.

share|improve this answer
i need the string to look exactly like that – Tom91136 Jul 11 '12 at 7:14

Using array_walk

$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);

IDEONE

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.