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.
In PHP, there are three types of arrays: Indexed arrays - Arrays with numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
$output = array_unique( array_merge( $array1 , $array2 ) );
The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.
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));
function parameterize_array($array) {
$out = array();
foreach($array as $key => $value)
$out[] = "$key=$value";
return $out;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With