Current Location: Home> Function Categories> array_diff

array_diff

Calculate the differences in arrays
Name:array_diff
Category:Array
Programming Language:php
One-line Description:Compare arrays and return the difference set (compare key values only).

array_diff function

Applicable to PHP version: PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8

Function description

The array_diff function is used to calculate the difference between two or more arrays. That is, return the value that exists in the first array but does not appear in other arrays.

Function Syntax

 <span class="fun">array_diff(array $array1, array $array2, array ...$arrays): array</span>

parameter

  • $array1 : The first array. It is the benchmark array to perform the difference set calculation.
  • $array2, ...$arrays : one or more arrays. Compare with the first array and return the values in the first array that are not in these arrays.

Return value

Returns a new array containing all values that exist in the first array but are not in other arrays.

Example

Here is an example using the array_diff function:

 <?php
$array1 = [1, 2, 3, 4, 5];
$array2 = [4, 5, 6];
$array3 = [1, 6, 7];

$result = array_diff($array1, $array2, $array3);
print_r($result);
?>

Description of sample code

In the example above, $array1 contains integer values 1, 2, 3, 4, 5. $array2 contains integer values 4, 5, 6, while $array3 contains integer values 1, 6, 7. After calling the array_diff function, the returned result is an element contained in $array1 but not in $array2 and $array3.

After execution, the output will be:

 Array ( [0] => 2 [1] => 3 ) Explanation: 2 and 3 appear in $array1, but not in $array2 and $array3, so they are included in the return value. Array ( [0] => 2 [1] => 3 )

Similar Functions
Popular Articles