Home > Article > Backend Development > How to use array_diff function to get the difference set in PHP
In PHP, array is a very common data type, usually used to store a set of related data. In actual development projects, it is often necessary to compare multiple arrays and extract their differences. At this time, you can use the array_diff function in PHP to achieve this.
array_diff function is a function used in PHP to find the difference between two or more arrays. Its specific usage is as follows:
array_diff (array $array1 , array $array2 [, array $... ]) : array
Among them, the parameter $array1 is to be compared. Base array, $array2 is the array to be compared with the base array, and the subsequent parameter $... can continue to pass in other arrays that need to be compared. This function will return all elements that are different from the base array into a new array.
Let’s take a look at how to use the array_diff function to find the difference between two arrays through an example.
<?php $array1 = array("a" => "apple", "b" => "banana", "c" => "cherry"); $array2 = array("b" => "banana", "c" => "cherry", "d" => "date"); $result = array_diff($array1, $array2); print_r($result); ?>
The output result of the above code is:
Array ( [a] => apple )
As you can see, since there is only one element "a" in $array1 that is different from $array2, the array_diff function returns only the element "a" new array.
In addition to passing in two arrays, the array_diff function can also pass in multiple arrays for comparison. Let's look at an example of passing in three arrays:
<?php $array1 = array("a" => "apple", "b" => "banana", "c" => "cherry"); $array2 = array("b" => "banana", "c" => "cherry", "d" => "date"); $array3 = array("b" => "banana"); $result = array_diff($array1, $array2, $array3); print_r($result); ?>
The output result of the above code is:
Array ( [a] => apple [c] => cherry )
As you can see, among the three arrays, there is only the element "a of $array1 " and "c" are different from other arrays, so the array_diff function returns a new array containing these two elements.
It is important to note that the array_diff function compares the key values of the array, not just the values. That is, two elements are considered the same only if their keys and values are the same. If you want to compare only the values of arrays, you can use functions such as array_diff_key, array_diff_assoc, and array_udiff.
In summary, the array_diff function is a function used to compare the differences between multiple arrays and return different elements. For scenarios that require array comparison in PHP, the array_diff function is a very practical tool.
The above is the detailed content of How to use array_diff function to get the difference set in PHP. For more information, please follow other related articles on the PHP Chinese website!