简体   繁体   中英

Why does the array have an extra “[index] => ” in the end, and array_combine error

I am using array_combine() function on two arrays, and using the following code :

if (($line = fgetcsv($file)) !== FALSE) {
    //$line is an array of CSV elements
    print_r($line);
    print_r($slots_for_quiz);
    $combined_array = array_combine($slots_for_quiz, $line);
    print_r($combined_array); //check 
} else {echo 'FALSE';}

The output is:

Array ( [0] => Alpha [1] => Beta [2] => Gamma [3] => )  Array ( [0] => 1 [1] => 2 [2] => 3 ) 
Warning: array_combine(): Both parameters should have an equal number of elements

So we can see that $line is: Array ( [0] => Alpha [1] => Beta [2] => Gamma [3] => )

and $slots_for_quiz is: Array ( [0] => 1 [1] => 2 [2] => 3 )

My question is 1. Why am I getting [3] => in the end of $line (this is not even an associative array). 2. About the warning: why does it say that my arrays do not have same number of elements. Both of them have 3 elements, isn't it?

Maybe you could do something like:

$line = array_filter($line);
$combined_array = array_combine($slots_for_quiz, $line);

Should remove that empty value, and probably line it up now correctly.

Or you could just pop it.

array_pop($line);
$combined_array = array_combine($slots_for_quiz, $line);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM