How to Compare Two or More Array Values in PHP

Compare Array PHP

Before we compare arrays in PHP, You should know about the array_diff() function of PHP. Let’s see the definition, syntax, and examples of array diff() function of PHP

PHP array_diff() Function

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

.

Syntax

The syntax of array_diff() function is following:

array_diff(array_one, array_second, array_third, …, array_n);

Parameters of array_diff() function:

Parameter
array_one
array_second
Description
This is required. The array to compare from.
This is required. An array to compare against.

Example 1 – Compare two arrays in PHP

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

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

The result of the above code is: Array ( [4] => five )

Example 2 – Compare Numeric Array in PHP

Let’s take the second example, in this example, we have two numeric arrays with duplicate values. And we will remove the duplicate values from these arrays and create a new unique array in PHP:

<?php
$array_one = array(1, 2, 3, 4, 5, 6);
$array_second = array(1, 2, 3, 4);
 
$res = array_diff($array_one,$array_second);
 
print_r($res);
?>

The result of the above code is: Array ( [4] => 5 [5] => 6 )

Example 3 – Compare Three Arrays in PHP

Let’s take the Third example, in this example, we have three arrays with duplicate values. And we will compare these three arrays and find the difference between PHP:

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

The output of the above code is: Array ( [2] => c [3] => d [4] => e )

Leave a Reply

Your email address will not be published. Required fields are marked *