nexuscreator
nexuscreator

Reputation: 845

php compare two associative arrays using array_intersect()

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']));

Upvotes: 1

Views: 4204

Answers (1)

user3415653
user3415653

Reputation: 335

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

Upvotes: 3

Related Questions