Skip to content
Home » Search for Multiple Values in PHP Array | 2023 Code Examples

Search for Multiple Values in PHP Array | 2023 Code Examples

Functions Mentioned in this Post

How to search for multiple values in a PHP array

  1. Create a variable that includes the array to be searched
  2. Create a separate variable that includes all of the values you want to search and find.
  3. Set a new variable that will include all of your final results
  4. Run the array_intersect function passing the array to be searched as the first parameter and the searching array as the second parameter.
  5. Assign the array_intersect results to your final results variable.
  6. Verify your results with a print_r or var_dump statement.
  7. Remove the print_r statement and continue processing requirements

Searching multiple values in a PHP array Code Snippet

<?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
)
*/
 
 
?>

Search PHP Arrays for Multiple Values Options Compared

array_intersectarray_filterforeach loop
Readability Score
(1-5)
532
Time
(1 million executions)
.63 mins1.18 mins3.5 mins
PHP Version4.0.14.0.64
Functions to process123
Recommendationpreferredsometimesavoid

Test Processing Time Code Snippet

The following is the code snippet I used to test the 1 million executions. I ran it on an EC2 instance with 1cpu and 2g RAM

<?php 
$original = [];
$toSearch = [];
$final = [];

// Let's generate some values for our original array
for ($i = 0; $i < 100; $i++) {
 $original[] = $i;
 }

// Let's generate some values for our toSearch array
for ($i = 0; $i < 20; $i++) {
$toSearch[] = rand(0, 200);
}


//
// Test the array_filter function
///
//
$time_start = microtime(true); 

// Run 1000000 executions
for($i=0; $i<1000000; $i++){
 $intersection_arr = array_filter($original, function($val) use($toSearch) {
    return in_array($val, $toSearch);
});
}



$time_end = microtime(true);


//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';



//
// Test the array_intersect function
//
//

$time_start = microtime(true); 

// Run 1000000 executions
for($i=0; $i<1000000; $i++){
    //It would contain the result of the array_filter intersection
    $intersection_arr = array_intersect($original, $toSearch);
}



$time_end = microtime(true);


//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';



//
// Test the foreach loop method
//
//

$time_start = microtime(true); 

// Run 1000000 executions
for($i=0; $i<1000000; $i++){
    
    foreach($toSearch as $search)
    {
        //If a country in the $search_values exist in $country_arr
        if(in_array($search,$original))
        {
           $final[] = $search;
        }
    }
}



$time_end = microtime(true);


//dividing with 60 will give the execution time in minutes otherwise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';

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 a PHP array.

Search for multiple values in PHP array using a foreach loop

  1. Create a variable that includes all the values in a $fullList array that contains all the values.
  2. Define the values you want to search in a separate $searchable array.
  3. Instantiate a final searched array called $intersectionArray
  4. Iterate through the base $fullList array with a foreach loop
  5. Use the in_array function in an if statement to see if any of the $searchable elements exist in the current $fullList array
  6. Add the value to the $intersectionArray when the in_array function returns true.
  7. Do a var_dump of the intersection array when complete.

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.

Search for multiple values in a 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.

Find a particular subset of values in a PHP Array with array_filter

<?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.

Find a subset of values qualifying a particular condition in a PHP array using array_filter

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.

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.

Search & Find a particular subset of values in a PHP array using the array_intersect function

<?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