How to search for multiple values in PHP array

Summary:

There are several methods you can use to search inside of a PHP array. We recommend using the array_filter or array_intersect methods for single-dimensional arrays. You will need to use recursion to deep search a multidimensional array. Check out the article for more details.

Code Snippet: Searching multiple values in a PHP array

<?php
 
//An array with random country names.
$country_arr = array("USA","Canada","Mexico","Germany","Italy");
 
// 2 Options Available:

// #1 - array_filter function 
//It would contain the result of the array_filter intersection
// Let's check if the country array contains any of the passed array items.

// The array_filter method is a good option for this.
$intersection_arr = array_filter($country_arr, function($country) {
    return in_array($country,["USA","Canada","France"]);
});
 
print_r($intersection_arr);
 
/*
OUTPUT
Array
(
    [0] => USA   
    [1] => Canada
)
*/
 


// Option #2: array_intersect function
 
//Look for these values and return the intersection.
$search_values = ["USA","Canada","France"];
 
//It would contain the result of the array_filter intersection
$intersection_arr = array_intersect($country_arr,$search_values);
               
 
print_r($intersection_arr);
 
/*
OUTPUT
Array
(
    [0] => USA
    [1] => Canada
)
*/
 
 
?>

The above code snippet shows 2 options you can use to search multiple values within a PHP array. These solutions assume you aren’t deep searching into a nested array. You will need to use recursion and be considerate of your performance if you want to do a deep search. The array_filter and array_intersect functions are both good options for most use cases where you need to do a quick search.

Sidebar: How’s Your Programming Career Going?

We’ve created a free career guide for those that are looking to make the most of their programming careers. We’re continuously updating this resource to help you level up and create clarity in your career roadmap. This is great content whether you are new to programming or have been in the field for 20 years. We are seasoned veterans with many years of software engineering under our belt.

Click here to check out our career guide.

Relevant Content on Array Searching

We have seen a bunch of array operations so far and most of the time there are several options to go about a problem. In this article, we’ll explore how to search for multiple values in a PHP array. We have seen similar articles. You can check them out if you need to.

These articles deal with a search that involves looking up an array for a value. Here we have a slightly different scenario. We have multiple values, and we have to search these values in an array.

Solutions to searching multiple values in PHP array

There are several interpretations of “search for multiple values in a PHP array”. The search could be for : 

  • A particular subset of values. (Intersection)
  • A subset of values qualifying a particular condition. (Query)

We’ll try to look at the subject from all these perspectives.

So without any further ado, let’s see how to search multiple values in array PHP.

Option 1: Search for multiple values in PHP array using a foreach loop

A foreach loop is the first thing that comes to mind when we have associative arrays. It is genuinely inevitable, and PHP developers and programmers have to resort to it even if PHP provides a specialized function for an operation.

The reason is that the foreach loop gives much freedom to play around with the keys and values of an associative array. Here we’ll use it to search multiple values in array PHP.

Example: Find a particular subset of values in PHP array

In this example, we’ll see how to search an array for a subgroup of values. This problem perspective seeks a group of elements within an array and returns those it finds successfully. 

This operation is similar to the intersection between two sets. If you’ve ever studied set theory in your school, you can relate pretty well. The following figure clarifies this perspective.

search for multiple values in PHP array
<?php
 
//An array with random country names.
$country_arr = array("USA","Canada","Mexico","Germany","Italy");
 
//Look for these values and return the intersection.
$search_values = ["USA","Canada","France"];
 
//It would contain the intersection of these two arrays.
$intersection_arr = [];
 
foreach($search_values as $country)
{
    //If a country in the $search_values exist in $country_arr
    if(in_array($country,$country_arr))
    {
       array_push($intersection_arr,$country);
    }
}
 
print_r($intersection_arr);
 
/*
OUTPUT
Array
(
    [0] => USA
    [1] => Canada
)
*/
 
?>

The example finds the intersection between the two arrays and returns the common values. Notice that we’ve used the in_array function that returns true if a country exists in the $country_arr.

Example: Find a subset of values in PHP array qualifying a particular condition

This operation is similar to a query if you’re familiar with databases. It is okay if you’re not aware because it means looking up data based on some rule or criteria. Here are a few possible queries that fit in the context.

  • Search countries with names having more than five letters.
  • Search countries with names starting from the letter “A”.
  • Find countries with names ending with the letter “A.”

These are just a few examples, and you’ll deal with many more such examples if you’re working on a real time data intensive application. Let’s do an example and find multiple values in array PHP whose names have more than five letters.

search for multiple values in PHP array
<?php
 
//An array with random country names.
$country_arr = array("USA","Canada","Mexico","Germany","Italy");
 
 
//It would contain the result of the query.
$resultant_arr = [];
 
foreach($country_arr as $country)
{
    //If a country name has more than five letters
    if(strlen($country) > 5)
    {
        array_push($resultant_arr,$country);
    }
}
 
print_r($resultant_arr);
 
/*
OUTPUT
Array
(
    [0] => Canada 
    [1] => Mexico 
    [2] => Germany
)
*/

?>

Great! It queries the array and searches for multiple values that qualify the query condition. Let’s explore more options to find multiple values in array PHP.

Option 2: Search for multiple values in PHP array using array_filter

PHP array_filter is a powerful function. It usually does an equivalent of the foreach loop, and that too in a one-liner. It takes a callback function, and based on the return boolean type, it decides to either keep or discard a value. 

We will jump straight into examples and try to redo the scenarios we did in the previous section. This approach would enable us to draw a contrast between the two options.

Example#1  – Find a particular subset of values

<?php
 
//An array with random country names.
$country_arr = array("USA","Canada","Mexico","Germany","Italy");
 
 
//It would contain the result of the array_filter intersection
$intersection_arr = array_filter($country_arr, function($country)
                {
                   return in_array($country,["USA","Canada","France"]);
                    
                });
 
print_r($intersection_arr);
 
/*
OUTPUT
Array
(
    [0] => USA   
    [1] => Canada
)
*/
 
 
?>

You can see that the code becomes much shorter and cleaner. The array_filter approach is quite sophisticated comparing to the foreach loop. Let’s also try the second scenario.

Example#2  – Find a subset of values qualifying a particular condition

Here’s a contrasting example of the query example we did in the foreach section.

<?php
 
//An array with random country names.
$country_arr = array("USA","Canada","Mexico","Germany","Italy");
 
 
//It would contain the result of the array_filter intersection
$intersection_arr = array_filter($country_arr, function($country) {
    return strlen($country) > 5;
});
 
print_r($intersection_arr);
 
/*
OUTPUT
Array
(
    [1] => Canada
    [2] => Mexico
    [3] => Germany
)
*/
 
 
?>

Look how conveniently it does the query function, with much less hassle. Now is the time to move to the third option.

Option #3: Find multiple values in a PHP array using array_intersect function.

PHP provides a function for intersecting two different arrays. The function that we are going to see her is the array_intersect function.

Description

Finds the intersection of two arrays

Function Signature

array_intersect(array $array, array ...$arrays): array

Arguments

  • $array   – The master array
  • $arrays – Arrays to compare values against

Return Type

The function returns the intersection array of the main with all the arrays in the second argument.

Example  – Find a particular subset of values in a PHP array

<?php
 
//An array with random country names.
$country_arr = array("USA","Canada","Mexico","Germany","Italy");
 
 
//Look for these values and return the intersection.
$search_values = ["USA","Canada","France"];
 
//It would contain the result of the array_filter intersection
$intersection_arr = array_intersect($country_arr,$search_values);
               
 
print_r($intersection_arr);
 
/*
OUTPUT
Array
(
    [0] => USA
    [1] => Canada
)
*/
 
 
?>

A quick function call finds the intersection between the two arrays. Handy, isn’t it?

Conclusion

In this article, we have seen how to search for multiple values in PHP array. We have explored the intersection and query perspective of the problem and used three different options to find multiple values in array PHP. The options we’ve explored include foreach loop, array_filter, and array_intersection functions. We hope you’ve learned something new today. Stay tuned for more interesting content related to PHP.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to filter array of objects by value in PHP

How to filter array of objects by key in PHP

Difference between while and do-while loops in PHP

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems