In daily development, array_diff() is a very practical PHP built-in function. It can be used to compare two or more arrays, returning values in the first array but not in the subsequent array. This is very common in scenarios such as filtering data, comparing list differences, etc.
So the question is: Will array_diff() perform strict type matching when comparing values? In other words, items with different types but the same value will be considered the same or different?
In PHP, array_diff() uses "non-strict" comparison, that is, it does not compare their data types when judging whether two values are equal, but only focuses on whether the values are "equal".
This comparison method is called "loose comparison" in PHP, and it behaves similarly to judgments made using the == operator, rather than === .
<?php
$array1 = [1, 2, 3, "4"];
$array2 = ["1", 2, 4];
$result = array_diff($array1, $array2);
print_r($result);
?>
Array
(
[2] => 3
[3] => 4
)
In this example:
1 (integer) and "1" (string) are considered equal and are therefore filtered out.
3 and "3" are not in $array2 , so reserved.
"4" and 4 are considered equal and are also filtered out.
Conclusion: PHP's array_diff() does not perform strict type comparison.
Although array_diff() itself does not support strict comparison, PHP provides another function array_diff_assoc() , which compares key names in addition to comparing values.
However, if we only care about strict comparison of values, we can use array_udiff() to achieve strict comparison with a custom comparison function.
<?php
$array1 = [1, 2, 3, "4"];
$array2 = ["1", 2, 4];
$result = array_udiff($array1, $array2, function ($a, $b) {
if ($a === $b) return 0;
return ($a > $b) ? 1 : -1;
});
print_r($result);
?>
Array
(
[0] => 1
[2] => 3
[3] => 4
)
In this example, 1 (int) and "1" (string) are treated as different values , so 1 is preserved. This achieves the purpose of strict type comparison.
Suppose you have a list of product IDs uploaded by the user (all strings), and you want to remove the IDs (integrals) that already exist in the database. You can avoid incorrect matching in strict matching:
<?php
$uploadedIDs = ["101", "102", "103"];
$existingIDs = [101, 104];
$diff = array_udiff($uploadedIDs, $existingIDs, function ($a, $b) {
return $a === $b ? 0 : ($a > $b ? 1 : -1);
});
// Suppose you need to construct one URL Show the rest ID
$url = "https://m66.net/products?ids=" . implode(",", $diff);
echo $url;
?>
Output URL:
https://m66.net/products?ids=101,102,103
array_diff() uses loose comparisons, regardless of type differences;
If you need to strictly match the value type, you can use array_udiff() with a custom comparison function;
When dealing with user data and type-sensitive data filtering, it is recommended to use strict comparisons to avoid logical vulnerabilities.
Hope this article will be helpful for you to understand the behavior mechanism of array difference functions in PHP!