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 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
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:
array- the first array from which to compare.
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.
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 (  => 1 ) print_r($diff2); // Output: Array (  => 4 ) print_r($diff3); // Output: Array (  => 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
In this post, we discovered the functionality and usage of the
array_diff() method to calculate the difference between two or more arrays.