PHP array_diff() Function

PHP array_diff()  function is “used to compare the values of two (or more) arrays.” It returns the values in the first array that are not present in any of the other arrays.

Syntax

array_diff($array1,$array2,$array3...);

Parameters

$array1, $array2, $array3: The parameters array1 and array2 are required. From array3, the parameter is optional. The array1 parameter is the array to compare from, and the array2 is an array to compare against.

Visual RepresentationVisual Representation of PHP array_diff() Function

Example 1: How to Use PHP array_diff() function

<?php

$arr1 = [1, 2, 3, 4, 5];
$arr2 = [19, 21, 46, 4, 2];

$finalArray = array_diff($arr1, $arr2);

print_r($finalArray);

Output

Array
(
 [0] => 1
 [2] => 3
 [4] => 5
)

The above example repeats 2 and 4 items in both arrays. So, it will be eliminated from the final array, and the remaining array items from $arr1 are 1, 3, and 5. So the output $finalArray contains the [1, 3, 5] values.

Example 2: Compare three arraysVisual Representation of Compare three arrays

<?php

$arr1 = [1, 2, 3, 4, 5];
$arr2 = [19, 21, 46, 4, 2];
$arr3 = [11, 12, 13, 14, 3];

$finalArray = array_diff($arr1, $arr2, $arr3);

print_r($finalArray);

Output

Array
(
 [0] => 1
 [4] => 5
)

In this example, I have taken the third array called $arr3. It has only one value, 3, matching the array $arr1.  So, in the final array, item 3 is also eliminated, and we only see the two items, 1 and 5.

Example 3: Compare associative arrays

<?php

$arr1 = ['a' => 'krunal', 'b' => 'ankit'];
$arr2 = ['c' => 'rushabh', 'd' =>'dhaval'];
$arr3 = ['e' =>'Roy', 'f' => 'Glenn', 'g' => 'Jos'];

$finalArray = array_diff($arr1, $arr2, $arr3);

print_r($finalArray);

Output

Array
(
 [b] => ankit
)

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.