Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine the keys and values of an array in PHP

Tags:

arrays

php

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.

like image 234
nohat Avatar asked Sep 11 '09 22:09

nohat


People also ask

Which array has pair of value and key in PHP?

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.

How do I combine two values in an array?

$output = array_unique( array_merge( $array1 , $array2 ) );

How can I merge two arrays in PHP?

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.


2 Answers

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));
like image 194
Leonardo Prado Avatar answered Oct 16 '22 04:10

Leonardo Prado


function parameterize_array($array) {
    $out = array();
    foreach($array as $key => $value)
        $out[] = "$key=$value";
    return $out;
}
like image 40
chaos Avatar answered Oct 16 '22 03:10

chaos