Search code examples
phpforeacharray-combine

foreach array_combine two array by php


There are two arrays that One is the correct answers and the other is the user's answer.

My Php:

$i=1;
$correct = array('a','d','c','a','b','c');
$user    = array('a','c','c','a','c','c');

foreach (array_combine($correct, $user) as $co => $ur) {
    if($co == $ur) {
        echo $i.':true <br>';
    } else {
        echo $i.':false <br>';
    }
    $i++;
}
echo 'True: '.count($co == $ur);
echo 'False: '.count($co == $ur);

out:

1:true
2:false
3:true
4:false
Error: count(): Argument must be of type Countable...

Number 4 is wrong (It must be true). It does not show numbers 5 and 6 in the output. It also does not show the true and false numbers. I want to show the true and false result in the output.

My Out:

1: true
2: false
3: true
4: true
5: false
6: true

True: 4
False: 2

Solution

  • Array_Combine takes one array for the keys and one for the values. Duplicate keys won't be created and you have duplicate keys.

    Another solution is to loop through one array and compare it that way:

    $correct = array('a','d','c','a','b','c');
    $user    = array('a','c','c','a','c','c');
    
    $totals = ["correct" => 0,"incorrect" => 0];
    
    foreach($correct as $i => $answer){
        if($user[$i] == $answer){
            $totals["correct"] ++;
            echo "$i correct<br>";
        }
        else{
            $totals["incorrect"] ++;
            echo "$i incorrect<br>";
        }   
    }
    
    echo $totals["incorrect"] . " - incorrect<br>";
    echo $totals["correct"] . " - correct<br>";