I have an array in PHP
$permission = array( "admin", "moderator", "guest" );
and i have another array
$userRoles = array( "admin", "moderator" );
I checked with in_array
but it doesn't work with multiple values.
How can i check atleast one value in $userRoles
exists on $permission
without looping ?
Thanks in advance.
You can just use if (array_intersect($permission, $userRoles)) ... .
To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.
Use array_intersect
count(array_intersect($permission, $userRoles));
Use array_intersect
array_intersect — Computes the intersection of arrays
array
array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
Read
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With