Red
Red

Reputation: 6378

check multiple values exists php array

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.

Upvotes: 24

Views: 30664

Answers (2)

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

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

Upvotes: 14

Explosion Pills
Explosion Pills

Reputation: 191749

Use array_intersect

count(array_intersect($permission, $userRoles));

Upvotes: 41

Related Questions