The php array_combine() function creates a new array given two arrays, where one array is used for the keys and the other array is used for the values of the new array.

$array1 = array('bear', 'elephant', 'rabbit');
$array2 = array(1,2,3);
$new_array = array_combine($array1, $array2);

print_r($new_array);

// Output: 
Array
(
    [bear] => 1
    [elephant] => 2
    [rabbit] => 3
)

When working with collections of data in php, the ability to manipulate them and create new collections is very valuable.

One such manipulation is the ability to combine multiple arrays into a new array in php.

The php array_combine() function will take two arrays and “zip” them together where the first array passed to array_combine() will be used for the keys and the second array will be used for the values.

Below is a simple example in php showing how we can use the array_combine() function.

$array1 = array('bear', 'elephant', 'rabbit');
$array2 = array(1,2,3);
$new_array = array_combine($array1, $array2);

print_r($new_array);

// Output: 
Array
(
    [bear] => 1
    [elephant] => 2
    [rabbit] => 3
)

Duplicate Keys and array_combine()

If you have duplicate values in the array which will be the keys of the new array, array_combine() will keep the second key.

Below is an example of what happens when you have duplicate keys and try to use array_combine()

$array1 = array('bear', 'bear', 'rabbit');
$array2 = array(1,2,3);
$new_array = array_combine($array1, $array2);

print_r($new_array);

// Output: 
Array
(
    [bear] => 2
    [rabbit] => 3
)

To keep all of the values, you can define your own function which will take any duplicate keys and then create an array which will store all of the values for those duplicate keys.

Below is a function which will help you handle the case where you have duplicate keys and want to keep all of the values.

function array_combine_dup($keys, $values) {
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, function(&$v){ $v = (count($v) == 1) ? array_pop($v): $v; });
    return $result;
}

$array1 = array('bear', 'bear', 'rabbit');
$array2 = array(1,2,3);
$new_array = array_combine_dup($array1, $array2)

print_r($new_array);

// Output: 
Array
(
    [bear] => Array
        (
            [0] => 1
            [1] => 2
        )

    [rabbit] => 3
)

Hopefully this article has been useful for you to learn how to use the php array_combine() function.

Categorized in:

PHP,

Last Update: March 13, 2024