Expand To Show Full Article
PHP array_combine: how to use in PHP with examples - Fueling PHP
Skip to content
Home » Functions » PHP array_combine: how to use in PHP with examples

PHP array_combine: how to use in PHP with examples

What is PHP array_combine?

Description

PHP array_combine function creates an array by combining two arrays, one for key and another for values.

Function Signature

array_combine(array $keys, array $values): array

Arguments

  • $keys – An array of keys
  • $values – An array of values

Return Type

The function returns the combined array or false if the number of elements in $keys and $values are not equal.

Introduction – PHP array_combine

PHP array_combine is apparently a straightforward function. As the name suggests, it combines two arrays. However, the way it combines the two arrays is different than what we have seen while learning the PHP array_merge function. There the function merged the two arrays by joining the values while catering for similar keys using varying logic.

The array_combine function takes two arrays, one for keys and another for values. So, it takes creates an associative array using keys from the first array argument and values from another. This feature is handy, unique, and useful in some scenarios, imagine defining headers for a CSV or key/values for JSON.

PHP array_combine

In this article, we will explore array_combine in PHP

Usage Example – PHP array_combine

Here’s a simple example of how to use PHP array_combine.

<?php
$keys = ["AU","BR","CA","US"];
$values = ["Australia","Brazil","Canada","United States"];
 
$combined_arr = array_combine($keys,$values);
 
print_r($combined_arr);
 
/*
OUTPUT
Array
(
    [AU] => Australia    
    [BR] => Brazil      
    [CA] => Canada      
    [US] => United States
)
*/
?>

Here we go! The function takes the $keys array that includes country codes and a $values array with corresponding country names. The resulting associative array is a nice merger with key/value pairs representing country-codes/country-names.

So, the array_combine function does the work for us behind the scenes, which could’ve been done by us using a loop and some logic. Thanks to PHP for providing a shortcut. A more practical scenario for plugging in this function is defining headers for a CSV file. However, we need to discuss an important caveat of duplicate keys.

Important Caveat#1 – PHP array_combine

Let’s see the behavior of the function when we have duplication in the $keys array.

<?php
$keys = ["A","B","B","C"];
$values = [1,2,3,4];
 
$combined_arr = array_combine($keys,$values);
 
print_r($combined_arr);
 
/*
OUTPUT
Array      
(
    [A] => 1
    [B] => 3
    [C] => 4
)
*/
?>

The quirk here is that the recurring value occurring later takes precedence. So, the second duplicate key “B” pairs up with value 3. Sometimes we may need to modify this behavior and group values for the duplicate keys because the value 2 is lost here. So, let’s check out a solution that solves this problem

PHP array_combine: A workaround for duplicate keys

Here’s an implementation that behaves differently when encountering duplicate keys.

function array_combine_($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;
}

Basically, this function defines an array for every key in the $keys array. Why though? That’s the clever part because we need to group values for similar keys in a nested array. Finally, the array_walk function removes the unnecessary nesting while retaining nested arrays for duplicate keys.

Here’s the output of the previous code snippet that had duplicate keys. Note that the duplicate key groups the values.

/*
OUTPUT
Array      
Array
(
    [A] => 1
    [B] => Array
        (
            [0] => 2
            [1] => 3
        )
 
    [C] => 4
)
*/

Superb! Now we retain all the data without losing any.

Important Caveat#2 – PHP array_combine

Another important caveat is that array_combine in PHP throws an error if the count of $keys and $values arrays are not equal. So, we need a workaround for it as well. We need the function to be clever enough to deal with unequal arrays. 

We will experiment with the country-codes array from the usage example.

function array_combine_($a, $b)
{
    $acount = count($a);
    $bcount = count($b);
    $size = ($acount > $bcount) ? $bcount : $acount;
    $a = array_slice($a, 0, $size);
    $b = array_slice($b, 0, $size);
    return array_combine($a, $b);
}

The logic here is to equalize the arrays based on the shorter one. At least it won’t do erroneous matching when somethings missing at the end of the arrays. Here’s the test run of this function.

<?php
$keys = ["AU","BR","CA"];
$values = ["Australia","Brazil","Canada","United States"];
 
$combined_arr = array_combine_($keys,$values);
 
print_r($combined_arr);
 
/*
OUTPUT
Array
(
    [AU] => Australia
    [BR] => Brazil
    [CA] => Canada
)
*/
?>

Thanks to the newly defined function, it merges the array without raising any exceptions.

Conclusion

In this article, we have seen PHP array_combine function through an example and also discussed some important caveats concerning it. We have seen alternate implementations to overcome the inherent limitation in the array_combine. So, if you’ve made it to the conclusion then CONGRATULATIONS for learning a new PHP function today. Stay tuned for more interesting PHP articles and tutorials.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

PHP array_merge: How to use with examples in PHP

The difference between array_walk and array_walk_recursive in PHP

PHP array_filter: How to use with examples in PHP