I have array with values, e.g.
$parameters = ['G', 'W', 'G'];
and now I need to check if another array has these values. $parameters
can have duplicated values and can be in random order so if I'll check these values are in array
$array = ['W', 'G', 'G'];
it should return true
but on check with
$array2 = ['W', 'G'];
should return false
How to best do this? I have idea for create $array
with count for every letter, next count of every value in $parameters
and compare it. Is it a good way?
If I'm correct, you need to compare two arrays for same content without caring for the order. Check this:
if (count(array_diff(array_merge($parameters, $array), array_intersect($parameters, $array))) === 0) {
/**... */
}
Your idea is good: its algorithmic complexity is O(n + m)
, and it is really easy to implement using the array_count_values()
function and the equality operator:
function compareArrayFrequency(array $a, array $b): bool {
return array_count_values($a) == array_count_values($b);
}