PHP array_diff() Function
PHP array_diff() Syntax
array_diff(array $array, array ...$arrays): array
PHP array_diff() Basic examples
var_dump(array_diff([1,2,3], [2]));
array(2) {
[0]=> int(1)
[2]=> int(3)
}
Returns values present in the first array but not in the second.
PHP array_diff() Real-world usage
$allowed = ['read','write'];
$requested = ['read','delete'];
var_dump(array_diff($requested, $allowed));
array(1) {
[1]=> string(6) "delete"
}
Detects unsupported permissions.
PHP array_diff() Edge cases
var_dump(array_diff(["1", 1], [1]));
array(0) {
}
Comparison is non-strict and values are considered equal.
PHP array_diff() Common mistakes
Expecting key comparison
array_diff compares values only.
array_diff(['a'=>1], ['b'=>1]);
array_diff_assoc(['a'=>1], ['b'=>1]);
Use array_diff_assoc for key comparison.
PHP array_diff() Frequently Asked Questions
What does array_diff() do in PHP?
array_diff() returns the values from the first array that are not present in any of the other arrays.
What is the syntax of array_diff()?
array_diff(array $array, array ...$arrays): array
Does array_diff() preserve array keys?
Yes, array_diff() preserves the keys from the first array.
Is array_diff() case-sensitive?
Yes, comparisons are case-sensitive by default.
Does array_diff() compare keys or values?
array_diff() compares only values, not keys.
What happens with duplicate values in array_diff()?
All matching values found in other arrays are removed, including duplicates.
Can array_diff() work with multiple arrays?
Yes, you can pass multiple arrays to compare against.
Does array_diff() modify the original array?
No, it returns a new array without modifying the original.
What is the difference between array_diff() and array_diff_assoc()?
array_diff() compares only values, while array_diff_assoc() compares both keys and values.
Can array_diff() be used with associative arrays?
Yes, but only values are compared; keys are ignored.
What is a real-world use case of array_diff()?
Finding missing items, filtering datasets, or comparing lists.
Can array_diff() be combined with other functions?
Yes, it is often used with array_intersect() or array_filter() for data processing.
PHP array_diff() Related PHP Functions
-
array_allLearn more about array_all
-
array_anyLearn more about array_any
-
array_change_key_caseLearn more about array_change_key_case
-
array_chunkLearn more about array_chunk
-
array_diff_assoc PHP examplesLearn more about array_diff_assoc PHP examples
-
array_diff_key PHP examplesLearn more about array_diff_key PHP examples