1

I have two associative arrays. In fact, both are obtained after json decoding.I'm comparing for the presence of same data in both array and obtaining their count. The array_intersect method is giving incorrect result. The count should have been 2 but its giving 4. Please point where I am wrong.

Arrays:

Array ( [question_0] => b [question_1] => b [question_2] => a [question_3] => c )

Array ( [question_0] => a [question_1] => b [question_2] => b [question_3] => c [question_4] => c )

Code:

$temp = '{"question_0": "b",
        "question_1": "b",
        "question_2": "a",
        "question_3": "c"
        }';

$a = json_decode($temp,true);
print_r($a);

require_once "classes/config.readonly.php";
$data['token'] = '61db6e01cdd809e65e0490158b569b69';
$sql = "SELECT * FROM quiz_logger where token = " . "'" . $data['token'] . "'" ;
$db->query($sql);
while($row = $result->fetch_object() ){
    $answers = $row->data;
}

$ans = json_decode($answers,true);
print_r($ans['data']);

echo count(array_intersect($a, $ans['data']));

1 Answer 1

3

array_intersect is only comparing the values

try to use array_intersect_assoc https://www.php.net/manual/en/function.array-intersect-assoc.php

echo count(array_intersect_assoc($a, $ans['data']));

array_intersect_assoc is comparing keys and values, I think this is what you want

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

1 Comment

array_intersect compares values, not keys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.