array_combine()
“You’ve got your values with my keys!”
“You’ve got your keys with my values!”
Mmmm…
Use the values of one array as the keys, and the values of another array as the values, and get a brand new array from the combination.
The stipulations are:
- The two arrays must have the same number of elements
- The keys will be converted to string if necessary
- Keys of an integer in string format will become a numeric key
- Values will be overwritten on duplicate keys
As you’ll see here, the keys of your original arrays do not matter. Only the values are combined to create the new array.
$a1 = array('one' => 1, 'two' => 2, 'three' => 300, 'four' => 'the', 'five' => 'end'); $a2 = array('a' => 'apple', 'b' => 'banana', 'c' => 'carrot', 'd' => 'dandelion', 'e' => 'eggplant'); $arr = array_combine($a1, $a2); /* array ( 1 => 'apple', 2 => 'banana', 300 => 'carrot', 'the' => 'dandelion', 'end' => 'eggplant' ) */
An example of overwriting duplicate keys. Note that the resulting array has only four elements.
$a1 = array('one' => 1, 'two' => 2, 'three' => 300, 'four' => 'the', 'five' => 300); $a2 = array('a' => 'apple', 'b' => 'banana', 'c' => 'carrot', 'd' => 'dandelion', 'e' => 'eggplant'); $arr = array_combine($a1, $a2); /* array ( 1 => 'apple', 2 => 'banana', 300 => 'eggplant', 'the' => 'dandelion' ) */
For the keys, false will become the empty string, true will become one (1), integers in quotes will become numeric (even negative), floats will become strings.
$a1 = array('a', false, 0, -4, '-6', true, 'two words', '@#$', '4.5', 3.5); $a2 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 0); $arr = array_combine($a1, $a2); /* array ( 'a' => 1, '' => 2, 0 => 3, -4 => 4, -6 => 5, 1 => 6, 'two words' => 7, '@#$' => 8, '4.5' => 9, '3.5' => 0 ) */
See the manual entry for array_combine()
