How to combine keys and array values ​​in PHP

Let's say I have an array of key / value pairs in PHP:

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

What is the easiest way to convert this to an array that looks like this?

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

i.e.

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

In perl, I would do something like

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

Is there something similar in panoply array functions in PHP? Nothing I looked seemed like a convenient solution.

+5
source share
5 answers
function parameterize_array($array) {
    $out = array();
    foreach($array as $key => $value)
        $out[] = "$key=$value";
    return $out;
}
+9
source

Another option for this problem: in PHP 5.3+ you can use array_map()with closure (you can do it with PHP up to 5.2, but the code will be quite confusing!).

"Oh, but on array_map()you only get the value!"

, , !:)

$arr = array( 'foo' => 'bar', 'baz' => 'qux' );
$result = array_map(function($k, $v){
    return "$k=$v";
}, array_keys($arr), array_values($arr));
+13

"" = 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, '', '::' ) ) );
+3

The answer to chaos is good and straightforward. For a more general sense, you might have missed the function array_map()that you specified with your example map { "$_=$hash{$_}" } keys %hash.

0
source
    $user = array('name' => 'Bob Smith',
                  'age'  => 47,
                  'sex'  => 'M',
                  'dob'  => '5/12/1956'
                  );

    $Updates = explode("&" , urldecode(http_build_query($user)));

    var_dump($Updates);
0
source

All Articles