Definition and Usage
- PHP Version
- 4.0.1+
The array_diff() function finds the differences in array values between two or more arrays and returns a new array containing values that exist only in the first array.
This function is used to find the differences between arrays by returning values that do not exist in other arrays. By taking advantage of this behavior, it can also be used to remove specific values from an array.
It is commonly used for the following purposes.
- Removing duplicate values across arrays
- Checking differences between arrays
- Removing specific values from an array
Basic Example
/* Removing duplicate values across arrays */
$array1 = ['apple', 'banana', 'orange']; // The array used as the comparison base
$array2 = ['banana', 'apple', 'grape'];
$result = array_diff($array1, $array2);
print_r($result);
// Array ( [2] => orange )
// The keys in the returned array are preserved from the original comparison array
/* Checking differences between arrays */
$currentUserInfo = ['id' => 1, 'name' => 'John', 'age' => 30];
$updatedUserInfo = ['id' => 1, 'name' => 'John', 'age' => 31];
$differences = array_diff($updatedUserInfo, $currentUserInfo);
if (!empty($differences)) {
echo 'There are changes in the data. Updated fields: ';
foreach ($differences as $key => $value) {
echo "$key: $value ";
}
} else {
echo 'No changes were found.';
}
// Output: There are changes in the data. Updated fields: age: 31
/* Removing specific values from an array */
$originalArray = ['apple', 'banana', 'orange'];
$result = array_diff($originalArray, ['banana']);
print_r($result);
// Array ( [0] => apple [2] => orange )
Note:
The keys in the array returned by the array_diff() function are preserved from the original comparison array.
Syntax
array_diff(array $array_1, $array_2, $array_3, ...): array
Parameters
$array_1 |
Required. The array used as the base for comparison. |
|---|---|
$array_2 |
Required (optional as of PHP 8.0.0). An array to compare against the first array.
See Changes as of PHP 8.0.0. |
$array_3, ... |
Optional. Additional arrays to compare against the first array. Multiple arrays can be provided. |
Return Values
Returns an array containing values that exist only in the first array and are not present in the other arrays being compared. In this case, the keys of the returned array are preserved from the original comparison array.
If there are no values that exist only in the first array when compared to the other arrays, an empty array is returned.
$array1 = ['apple', 'banana', 'orange'];
$array2 = ['banana', 'apple', 'orange'];
$result = array_diff($array1, $array2);
print_r($result); // Array ( )
Changes as of PHP 8.0.0
As of PHP 8.0.0, the array_diff() function can be called with only a single parameter.
Previously, at least two parameters were required.
- Before PHP 8.0.0, at least two arrays always had to be passed as parameters.
- As of PHP 8.0.0, it is possible to pass only a single array.
$array1 = [1, 2, 3, 3, 4, 5, 5];
$unique = array_diff($array1);
print_r($unique);
/* Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 3
[4] => 4
[5] => 5
[6] => 5
)
*/
As shown in the example above, the array_diff() function is designed to calculate and return the differences between multiple arrays. However, when only a single array is provided, there is no array to compare against, so the entire array is returned. If duplicate values exist, those duplicates are preserved.
To remove duplicate values within a single array or to extract unique values, you can use the array_unique() function as shown below.
$array = [1, 2, 3, 3, 4, 5, 5];
$unique = array_unique($array);
print_r($unique);
/* Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
*/
Things to Keep in Mind
There are several important points to be aware of when using the array_diff() function.
Key and Value Comparison in Associative Arrays
The array_diff() function compares values only, so when working with associative arrays, values are retained even if the keys are different as long as the values match. This behavior can lead to situations that require special attention when using associative arrays.
$array1 = ['a' => 1, 'b' => 2, 'c' => 3];
$array2 = ['x' => 1, 'y' => 2, 'z' => 3];
$result = array_diff($array1, $array2);
print_r($result); // Output: Array ( )
In the example above, the array_diff() function compares values only, so an empty array is returned.
Even though the keys are different, all values match, resulting in no differences.
Therefore, when working with associative arrays, using the array_diff_assoc() function—which compares both keys and values—can be more explicit and behave more predictably.
| Function | Difference |
|---|---|
array_diff() |
Compares array values only, without considering keys. |
array_diff_assoc() |
Compares both array keys and values. |
Data Type Is Not Considered When Comparing Values
The array_diff() function compares values only and does not consider data types.
The following example illustrates this behavior.
$array1 = [1, 2, '3']; // '3' is stored as a string
$array2 = [1, 2, 3]; // 3 is stored as an integer
$differences = array_diff($array1, $array2);
print_r($differences); // Output: Array ( )
In the code above, $array1 and $array2 both contain the values '3' and 3, but their data types are different. The array_diff() function compares values only and does not take data types into account. As a result, even though the data types differ, no difference is detected, and an empty array is returned.
Practical Examples
The array_diff() function can be applied to a wide range of real-world scenarios.
Below are several practical examples that demonstrate how it can be used effectively.
Permission Checks
$user_permissions = ['read', 'write', 'delete'];
$required_permissions = ['read', 'execute'];
$missing_permissions = array_diff($required_permissions, $user_permissions);
if (empty($missing_permissions)) {
echo 'The user has all required permissions.';
} else {
echo 'The user is missing the following permissions: ' . implode(', ', $missing_permissions);
}
// Output: 'The user is missing the following permissions: execute'
Additional Explanation
The implode() function joins array elements into a string using a custom delimiter.
In this example, the list of required permissions is used as the reference to determine which permissions the user does not have.
Excluding Selected Options
$all_options = ['apple', 'banana', 'cherry', 'date'];
$selected_options = ['banana', 'date'];
$remaining_options = array_diff($all_options, $selected_options);
echo 'Unselected options: ' . implode(', ', $remaining_options);
// Output: 'Unselected options: apple, cherry'
Based on the options selected by the user, this example extracts only the options that were not chosen from the full list.
Cleaning Up Array Values
$raw_data = ['apple', 'banana', '', 'date', null, 'cherry'];
$cleaned_data = array_diff($raw_data, ['', null]);
print_r($cleaned_data);
/* Output:
Array
(
[0] => apple
[1] => banana
[3] => date
[5] => cherry
)
*/
This example removes empty strings ('') and null values from an array.
Because array_diff() does not perform strict type comparisons, the result may vary depending on the values being removed.
Finding Changed Files in Version Control
$committed_files = ['file1.php', 'file2.php', 'file3.php'];
$modified_files = ['file2.php', 'file3.php', 'file4.php'];
$new_files = array_diff($modified_files, $committed_files);
echo 'New files: ' . implode(', ', $new_files);
// Output: 'New files: file4.php'
In a version control context, this approach identifies new files that have been modified but not yet committed.
These examples demonstrate how array_diff() can be used to compare arrays and selectively process only the desired values. By choosing the appropriate reference array for each situation, array manipulation can be handled in a simple and predictable way.