1

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?

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

how exactly is this answer different from @TimBrown?
@user3415653 was earlier by ~6 years.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.