Checking to see if one array's elements are in another array in PHP
I have two arrays in PHP as follows:
People:
Array
(
[0] => 3
[1] => 20
)
Wanted Criminals:
Array
(
[0] => 2
[1] => 4
[2] => 8
[3] => 11
[4] => 12
[5] => 13
[6] => 14
[7] => 15
[8] => 16
[9] => 17
[10] => 18
[11] => 19
[12] => 20
)
How do I check if any of the People elements are in the Wanted Criminals array?
In this example, it should return true
because 20
is in Wanted Criminals.
You can use array_intersect()
.
$result = !empty(array_intersect($people, $criminals));
There's little wrong with using array_intersect() and count() (instead of empty).
For example:
$bFound = (count(array_intersect($criminals, $people))) ? true : false;