Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...