tags:

views:

105

answers:

3

Say I have an array of key/value pairs in PHP:

array( 'foo' => 'bar', 'baz' => 'qux' );

What's the simplest way to transform this to an array that looks like the following?

array( 'foo=bar', 'baz=qux' );

i.e.

array( 0 => 'foo=bar', 1 => 'baz=qux');

In perl, I'd do something like

map { "$_=$hash{$_}" } keys %hash

Is there something like this in the panoply of array functions in PHP? Nothing I looked at seemed like a convenient solution.

+4  A: 
function parameterize_array($array) {
    $out = array();
    foreach($array as $key => $value)
        $out[] = "$key=$value";
    return $out;
}
chaos
I accept this answer because it is straightforward, and how I ended up solving my problem. I am disappointed there is no way to do it in a single expression, avoiding the need for the temporary $out variable.
nohat
If you're a Perl user, this will be just one of the many, many disappointments you will encounter in the course of your experience with PHP.
chaos
@chaos Yeah, life is rough, and php is readable.@nohat Although this doesn't "transform" the array as your question stipulates. It makes a new one. "Panoply of array functions"? Giggle.
GZipp
@GZipp: Yeah, `$foo = isset($bar['baz']) ? $bar['baz'] : 'qxx'` is so much more readable than `$foo = $bar[baz] || 'qxx'`. Can't imagine what I was thinking.
chaos
Well, the "?:" operator was added to php so perlish coders could put everything on one line; I'd have thought you'd like that feature.
GZipp
I like the conditional operator fine. What I'm not as fond of is having crippled, brain-damaged logical OR and logical AND operators.
chaos
I see.
GZipp
A: 

chaos' answer is nice and straightfoward. For a more general sense though, you might have missed the array_map() function which is what you alluded to with your map { "$_=$hash{$_}" } keys %hash example.

Amber
array_map(), it seems, only gives you the array's values
nohat
Unfortunately, the strict equivalent code in PHP below 5.3 is a `create_function()`-using abomination.
chaos
Ah, nohat, if you need the keys then you might be able to use `array_walk()` instead (though that modifies the array in-place instead of returning a new array).
Amber
A: 

A "curious" way to do it =P

// using '::' as a temporary separator, could be anything provided
// it doesn't exist elsewhere in the array
$test = split( '::', urldecode( http_build_query( $test, '', '::' ) ) );
Peter Bailey