PHP Compare Arrays for Matches | array_intersect() Function
Php 07-Aug-2021

PHP Compare Arrays for Matches | array_intersect() Function

PHP compares arrays for matches. In this tutorial, you will learn how to compare two or more arrays in PHP and create new arrays with match values.

This tutorial has the purpose to explain to you compare two or more array in PHP with examples.

PHP Compare Arrays for Matches

Before we compare arrays in PHP for the match value, You should know about the array_intersect() function of PHP. Let’s see the definition, syntax, and examples of array_intersect() function of PHP

PHP array_intersect() Function

Definition:– The PHP array_intersect() function compares the values of two or more arrays values. And returns a new array with the match values.

Syntax

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 match

Let’s take the first example, in this example, we have two arrays with match values. And we will get the match values from these arrays and create a new array in PHP:

<?php
$array_one = array("first", "second", "third", "fourth", "five");
 
$array_second = array("first", "second", "third", "fourth");
 
$res = array_intersect($array_one,$array_second);
 
print_r($res);
?>

The result of the above code is: Array ( [0] => first [1] => second [2] => third [3] => fourth )

Example 2 – Compare Numeric Array in PHP

Let’s take the second example, in this example, we have two numeric arrays with match values. Using the array_intersect() function, we will get match values from these arrays and return a new array in PHP:

<?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 – PHP compare three arrays for matches

Let’s take the Third example, in this example, we have three arrays with match values. And it will return the match values from these three arrays in PHP using the array_intersect() method.

<?php
 
$array1 = array('a', 'b', 'c', 'd', 'e', 'f'); 
 
$array2 = array('a', 'b', 'g', 'h'); 
 
$array3 = array('a', 'b', 'i'); 
 
$res = array_intersect($array1, $array2, $array3);
 
print_r($res);
?>

The output of the above code is: Array ( [0] => a [1] => b )