Search
 
SCRIPT & CODE EXAMPLE
 

PHP

Searching the array for multiple values

# Searching the array for multiple values corresponds to the set operations (set difference and intersection), as you will see below.

# In your question, you do not specify which type of array search you want, so I am giving you both options.

# ALL needles exist
function in_array_all($needles, $haystack) {
   return empty(array_diff($needles, $haystack));
}

$animals = ["bear", "tiger", "zebra"];
echo in_array_all(["bear", "zebra"], $animals); // true, both are animals
echo in_array_all(["bear", "toaster"], $animals); // false, toaster is not an animal

# ANY of the needles exist
function in_array_any($needles, $haystack) {
   return !empty(array_intersect($needles, $haystack));
}

$animals = ["bear", "tiger", "zebra"];
echo in_array_any(["toaster", "tiger"], $animals); // true, tiger is an amimal
echo in_array_any(["toaster", "brush"], $animals); // false, no animals here

# Important consideration
/*
If the set of needles you are searching for is small and known upfront, your code might be clearer if you just use the logical chaining of in_array calls, for example:
*/
$animals = ZooAPI.getAllAnimals();
$all = in_array("tiger", $animals) && in_array("toaster", $animals) && ...
$any = in_array("bear", $animals) || in_array("zebra", $animals) || ...
Comment

PREVIOUS NEXT
Code Example
Php :: get number of chars ina string php 
Php :: How to fix undefined index: name in PackageManifest.php line 131 error with Composer 
Php :: orderby text values eliquent laravel 
Php :: file_get_contents url fail 
Php :: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 67108872 bytes) in phar:///usr/local/bin/composer1.phar/src/Composer/DependencyResolver/RuleSet.php on line 8 
Php :: laravel avoid logged in user to access a page 
Php :: Too Many Attempts. laravel error 
Php :: Notice: Undefined property: 
Php :: carbon add few hours 
Php :: how to find the name of login user in laravel 
Php :: laravel queue work on shared hosting 
Php :: concat and search in laravel eloquent 
Php :: Install the php_mysql extensions 
Php :: php capitalize each word 
Php :: laravel add utility class 
Php :: php session working on localhost but not on hosting server 
Php :: setcookie in laravel 8 
Php :: migration status php 
Php :: php check for empty string 
Php :: get order details by id woocommerce 
Php :: slp price php 
Php :: php clean all output buffers 
Php :: call to a member function connection() on null test laravel 
Php :: 24 hours date format php 
Php :: laravel create migration 
Php :: php replace every occurrence of character in string 
Php :: aravel 8 how to order by using eloquent orm 
Php :: query-data-from mysql and php 
Php :: wordpress get post by id 
Php :: php convert array to number 
ADD CONTENT
Topic
Content
Source link
Name
2+4 =