PHP array_diff() Function

In this tutorial, we will explore how we can use one of the built-in functions to calculate the difference of various input arrays.

PHP array_diff() Function

PHP or Hypertext Preprocessor is a server-side scripting language used to create dynamic web pages and web applications. It is open source and widely used for its simplicity and flexibility.

PHP provides us with a suite of tools and functions to perform a variety of programming concepts.

Let us dive in.

PHP Array_diff() Function

The PHP array_diff() function allows us to determine the difference between various input arrays. The functions syntax is as shown below:

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

The function accepts the following parameters:

  1. array - the first array from which to compare.
  2. array - defines the second array against which to compare.

The function will then return an array containing all the entries from the first array that are not present in the other arrays.

Example Code

Consider the code snippet show below that demonstrates the usage of the array_diff() method in PHP.

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

$diff1 = array_diff($array1, $array2, $array3);
$diff2 = array_diff($array2, $array1, $array3);
$diff3 = array_diff($array3, $array1, $array2);

print_r($diff1); // Output: Array ( [0] => 1 )
print_r($diff2); // Output: Array ( [2] => 4 )
print_r($diff3); // Output: Array ( [2] => 5 )

As you can see from the output above, the resulting arrays contain the values that are unique to each array. The values that are not present in the other two arrays.

NOTE: The function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);.

Conclusion

In this post, we discovered the functionality and usage of the array_diff() method to calculate the difference between two or more arrays.

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.