Say I have an array of key/value pairs in PHP:
array( \'foo\' => \'bar\', \'baz\' => \'qux\' );
What\'s the simplest way to transform
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, '', '::' ) ) );
Another option for this problem: On PHP 5.3+ you can use array_map()
with a closure (you can do this with PHP prior 5.2, but the code will get quite messy!).
"Oh, but on
array_map()
you only get the value!".
Yeah, that's right, but we can map more than one array! :)
$arr = array( 'foo' => 'bar', 'baz' => 'qux' );
$result = array_map(function($k, $v){
return "$k=$v";
}, array_keys($arr), array_values($arr));
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.
function parameterize_array($array) {
$out = array();
foreach($array as $key => $value)
$out[] = "$key=$value";
return $out;
}