foreach array_combine two array by php

32 views Asked by At

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
3

There are 3 answers

0
imvain2 On BEST ANSWER

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>";
0
Mubeen Ahmad On

Here's a corrected version:

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

$trueCount = 0;
$falseCount = 0;

for ($i = 0; $i < count($correct); $i++) {
    if ($correct[$i] == $user[$i]) {
        echo ($i + 1) . ': true <br>';
        $trueCount++;
    } else {
        echo ($i + 1) . ': false <br>';
        $falseCount++;
    }
}

echo 'True: ' . $trueCount . '<br>';
echo 'False: ' . $falseCount;

This should give you the desired output:

1: true
2: false
3: true
4: true
5: false
6: true
True: 4
False: 2
0
lukas.j On
$correct = [ 'a', 'd', 'c', 'a', 'b', 'c' ];
$user = [ 'a', 'c', 'c', 'a', 'c', 'c' ];

$result = array_count_values(
  array_map(
    static fn(string $c, string $u): int => (int)( $c === $u ),
    // or without type hints:
    // static fn($c, $u) => (int)( $c === $u ),
    $correct,
    $user
  )
);

echo $result[true];    // Output: 4
echo $result[false];   // Output: 2

The int cast is needed because array_count_values does not support counting booleans, only ints and strings.

If only the count for 'true' values is needed, this will do:

$result = array_sum(
  array_map(
    static fn(string $c, string $u): bool => $c === $u,
    // or without type hints:
    // static fn($c, $u) => $c === $u,
    $correct,
    $user
  )
);

echo $result;   // Output: 4