PHP array_diff() Function

Last Updated on August 28, 2021 by Roshan Parihar

PHP array_diff() Function is used to compare only the values of two or more arrays. After the comparison. After comparison, it returns the difference of the first array with other arrays without considering the keys.

It compares the values of the first array (array1) with the values of the rest of the arrays in PHP. After that, it returns the values of the first array (array1) that are not present in the rest of the arrays.

Let’s find out the use of the PHP array_diff() function with the examples given below.

Syntax of PHP array_diff() Function

array_diff(array1, array2, array3, …arrayN)

The array_diff() function takes comma-separated arrays as an argument.

Description of Parameters

Name Description
array1 Required. It is the first array to compare the values with other arrays.
array2 Required. Specify the second array to compare against.
array3…arrayN optional. Specify more arrays to compare against.

Let’s find out the use of the PHP array_diff() Function with the examples given below.

Examples of PHP array_diff() Function

See the examples given below to learn comparing the values of the arrays using the array_diff() Function in PHP.

Example 1: Compare the Difference of Values of Two Arrays in PHP

Suppose that, if you have two arrays to compare the difference of values, the PHP array_diff() function compares the values of the first array with the values of the second array. After the comparison, it returns the difference of values of the first array that are not present in the second array without considering the keys.

Output

Array ( [Bike] => 5 )

The above output shows that the value ‘5’ is not matching with the values of the second array regardless of keys. That’s why it prints that value in the output with its key.

Example 2: Get the Difference of Values from More than Two Arrays in PHP

In addition to the above example, you can also get the difference of values for more than two arrays using the PHP array_diff() function. It first compares their values to find the difference. After that, it returns the difference of the values of the first array that are not present in the second and third arrays.

Output

Array ( [Car] => 9 [WagonR] => 7 )

The above example contains the two elements whose values are different and not present in the second and third arrays in PHP.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

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