简体   繁体   中英

PHP check if array values match another array's values in the same position

I am creating a quiz with PHP. I have an answer key array and then I am building another array based on the user's answers. I want to compare both arrays and determine how many array values match the answer key array. I am currently using array_intersect() but this function doesn't seem to care about the index of the array values.

$user_answers = array(1,3,1);
$answer_key = array(3,1,1);
$result = array_intersect($user_answers, $answer_key);
echo count($result);

This returns 3 , but I want it to return 1 . How can I make it so that array_intersect is dependent on the index of the array values?

You should use array_intersect_assoc();

So your code would become...

$user_answers = array(1,3,1);
$answer_key = array(3,1,1);
$result = array_intersect_assoc($user_answers, $answer_key);
echo count($result);

Which will give a result of 1.

See: https://www.php.net/manual/en/function.array-intersect-assoc.php

array_intersect_assoc() function compare array and association key also. try following code

   $user_answers = array(1,3,1,5,8,8,7);
    $answer_key = array(3,1,1,5,7,9,7);
    $result = array_intersect_assoc($user_answers, $answer_key);
    echo count($result);

Output

3

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