Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check multiple values exists php array

Tags:

arrays

php

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.

like image 768
Red Avatar asked Mar 20 '13 04:03

Red


People also ask

How do I check if an array contains multiple values in PHP?

You can just use if (array_intersect($permission, $userRoles)) ... .

How do you check for multiple values in an array?

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 .

How do you check if a value exists in an array PHP?

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.

How can I find the difference between two arrays in PHP?

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.


2 Answers

Use array_intersect

count(array_intersect($permission, $userRoles));
like image 128
Explosion Pills Avatar answered Sep 28 '22 01:09

Explosion Pills


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

like image 30
Dipesh Parmar Avatar answered Sep 28 '22 02:09

Dipesh Parmar