The array_diff() function in PHP

The PHP array_diff() function is used to get the difference between an array with one or more arrays.

This function has the following syntax:

array_diff(array $array, array ...$arrays): array

The function parameters are as follows:

  • The $array to compare with the other parameters
  • The $arrays to compare against the first parameter

The values that are not found in the second parameter and the next will be returned by array_dif() function.

Here’s an example of calling the function:

$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 5];
$result = array_diff($array1, $array2);

print_r($result);

The print_r() result will be the differences between $array1 and $array2 as shown below:

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

You can compare the first parameter with multiple arrays like this:

$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 5];
$array3 = [1, 2];

// 👇 get the values unique to $array1
$result = array_diff($array1, $array2, $array3);

print_r($result);

The output is as follows:

Array
(
    [3] => 4
)

As you can see, you can pass as many arrays to compare with the first parameter as you need.

Keep in mind that this function only compares the array values in one dimension.

This means that if you have a multi dimension array, comparing the values will not work as easily.

And that’s how the array_diff() function works in PHP.

PHP has many functions that can be used to manipulate arrays. For example, the array_values() function is used to get the values of an array.

Another function named array_keys() can be used to grab the keys of an array.

By knowing about these functions, you can productively process an array using PHP. 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.