Warning: array_combine(): Both parameters should have an equal number of elements

This error appears when you try to combine two arrays with unequal length. As an example:

Array 1: Array (A, B, C)     //3 elements
Array 2: Array (1, 2, 3, 4)  //4 elements

array_combine() can’t combine those two arrays and will throw a warning.


There are different ways to approach this error.

You can check if both arrays have the same amount of elements and only combine them if they do:

<?php

    $arrayOne = Array("A", "B", "C");
    $arrayTwo = Array(1, 2, 3);

    if(count($arrayOne) == count($arrayTwo)){
        $result = array_combine($arrayOne, $arrayTwo);
    } else{
        echo "The arrays have unequal length";
    }

?>

You can combine the two arrays and only use as many elements as the smaller one has:

<?php

    $arrayOne = Array("A", "B", "C");
    $arrayTwo = Array(1, 2, 3);

    $min = min(count($arrayOne), count($arrayTwo));
    $result = array_combine(array_slice($arrayOne, 0, $min), array_slice($arrayTwo, 0, $min));

?>

Or you can also just fill the missing elements up:

<?php

    $arrayOne = Array("A", "B", "C");
    $arrayTwo = Array(1, 2, 3);

    $result = [];
    $counter = 0;

    array_map(function($v1, $v2)use(&$result, &$counter){
        $result[!is_null($v1) ? $v1 : "filler" . $counter++] = !is_null($v2) ? $v2 : "filler";     
    }, $arrayOne, $arrayTwo);

?>

Note: That in all examples you always want to make sure the keys array has only unique elements! Because otherwise PHP will just overwrite the elements with the same key and you will only keep the last one.

Leave a Comment