In this tutorial, you will learn how to compare two or more arrays in PHP and create new arrays with match values.
How to Compare Two or More Array for Matches in PHP?
You can use array_intersect()
function of PHP for that:
The PHP array_intersect()
function compares the values of two or more array values, and it returns a new array with the match values.
Here is syntax of array_intersect():
The syntax of array_intersect() function is following:
array_intersect(array_one, array_second, array_third, …, array_n);
Parameters of array_diff() function:
Parameter | Description |
---|---|
array_one | This is required. The array to compare from. |
array_second | This is required. An array to compare against. |
Example 1 – PHP Compare two arrays For a match
Let’s take the first example:
$array1 = array('apple', 'banana', 'orange', 'pear');
$array2 = array('banana', 'pear', 'grape', 'watermelon');
$common = array_intersect($array1, $array2);
print_r($common);
Example 2 – Compare Numeric Array in PHP
Let’s take the second example, in this example, you have two numeric arrays with match values:
<?php $array_one = array(1, 2, 3, 4, 5, 6); $array_second = array(1, 2, 3, 4); $res = array_intersect($array_one,$array_second); print_r($res); ?>
The result of the above code is: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
Example 3 – Compare three arrays for matches
Let’s take the third example for compare three array:
$array1 = array('apple', 'banana', 'orange', 'pear');
$array2 = array('banana', 'pear', 'grape', 'watermelon');
$array3 = array('pear', 'pineapple', 'kiwi', 'orange');
$common = array_intersect($array1, $array2, $array3);
print_r($common);
Conclusion
In conclusion, the array_intersect()
function is a useful tool for comparing arrays for matches in PHP.
Recommended Posts:
- Compare Arrays PHP | PHP array_diff() Function
- Get, Write, Read, Load, JSON File from Url PHP
- Functions: Remove First Character From String PHP
- Remove Specific/Special Characters From String In PHP
- How to Replace First and Last Character From String PHP
- Reverse String in PHP
- Array Push, POP PHP | PHP Array Tutorial
- PHP Search Multidimensional Array By key, value and return key
- json_encode()- Convert Array To JSON | Object To JSON PHP
- PHP remove duplicates from multidimensional array
- PHP Remove Duplicate Elements or Values from Array PHP