Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

I have a problem here in array_combine()

Warning: array_combine(): Both parameters should have an equal number of elements in PATH on line X

This error gets display on the following line:

foreach(array_combine($images, $word) as $imgs => $w)
{
    //do something
}

How can I fix it?

like image 490
Atashi Dubz Avatar asked Oct 16 '13 03:10

Atashi Dubz


1 Answers

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.

like image 134
Anand Solanki Avatar answered Oct 19 '22 22:10

Anand Solanki