0

In a question form, there is a checkbox for the options of the question. I use the checkboxes as the question has more than one correct answer. When POSTing this form information. (via JSON)

Sample:

{"session":"xxxx","selectedBoxes":["3","1"]}

On the server-side, I want to compare the incoming POST data with the data in the database.

On the server-side the correct answer to the question is stored as:

Sample:

{"0":"1","1":"3"}

The meaning of this data; The first and third options of question are correct.

In a small test environment, I tried:

$array1 = json_decode('{"0":"1","1":"3"}', true);
$array2 = array(3,1);
function array_equal_values(array $a, array $b)
{
return !array_diff($a, $b) && !array_diff($b, $a);
}

if (array_equal_values($array1, $array2) == true) {
    return true;
} else {
    return false;
}

Is this comparison a correct solution?

9
  • 2
    I think so. Instead of using array_diff() twice you could first assert that count($a) == count($b) and then just use array_diff() once. That makes it slightly easier to understand. Commented Apr 3, 2022 at 8:05
  • @KIKOSoftware was just writing the same comment :) Commented Apr 3, 2022 at 8:05
  • I would say though, if the array contained a large amount of items, count might not be the most efficient solution. You might try hashing both arrays and comparing their hashes. Commented Apr 3, 2022 at 8:09
  • @prog_24: Given where the data comes from I don't think efficiency should be a big concern. Also, what if the arrays are in a different order, as in the example? That would give two different hashes, even though the values might be the same. Sorting could solve that, but if you want something inefficient you should use sorting. Commented Apr 3, 2022 at 8:22
  • @KIKOSoftware that is a good point, anyway I believe you are on the right track, perhaps turn your first comment into an answer. Commented Apr 3, 2022 at 8:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.