The php array_diff() function allows us to find the elements of an array which are not in all of the other given arrays.

$array1 = array(5,3,8,2,1);
$array2 = array(9,3,4,2,1);

print_r(array_diff($array1,$array2));

// Output:
Array
(
    [0] => 5
    [2] => 8
)

When working with multiple arrays, it can be useful to find the entire collection of elements which are only in one array. The difference of one array with one or more arrays is the collection of elements which are only in the first array.

So, for example, if we have an array A and an array B, then the difference of A and B is a collection of elements which are in A but not in b.

We can get the difference of two arrays in php easily with the php array_diff() function.

Below is a simple example of how to use array_diff() to find the difference of two arrays in php.

$array1 = array(5,3,8,2,1);
$array2 = array(9,3,4,2,1);

print_r(array_diff($array1,$array2));

// Output:
Array
(
    [0] => 5
    [2] => 8
)

Finding the Difference of Three or More Arrays with array_diff() in php

The php array_diff() function can find the difference of more than two arrays.

The examples above only found the difference between two arrays, but we can find the difference of three or more arrays just as easy.

Below is an example of how to use array_diff() to find the differenec of three arrays in php.

Note, that array_diff() only looks at the first array, and is not finding the difference between the second or third array.

$array1 = array(5,3,8,2,1);
$array2 = array(9,3,4,2,1);
$array3 = array(0,9,8,1,3);

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

// Output:
Array
(
    [0] => 5
)

Hopefully this article has been useful for you to learn how to use the array_diff() function in php.

Categorized in:

PHP,

Last Update: February 26, 2024