How can check multiple values in array in php?

If you're looking to optimize this search with just a comparison check only I would do:

public function items_in_array[$needles, $haystack]
{
    foreach [$needles as $needle] {
        if [!in_array[$needle, $haystack]] {
            return false;
        }
    }

    return true;
}

if you're willing to do it ugly doing multiple if[in_array[...&&in_array[... is even faster.

I did a test with 100 and another with 100,000 array elements and between 2 and 15 needles using array_intersect, array_diff, and in_array.

in_array was always significantly faster even when I had to do it 15x for different needles. array_diff was also quite a bit faster than array_intersect.

So if you're just trying to search for a couple of things to see if they exist in an array in_array[] is best performance-wise. If you need to know the actual differences/matches then it's probably just easier to use array_diff/array_intersect.

Feel free to let me know if I did my calculations wrong in the ugly example below.

Chủ Đề