Home >Backend Development >PHP Tutorial >Tips for handling empty values and null values when deduplicating PHP arrays
Tips for handling empty and null values when deduplicating PHP arrays: Use array_unique with array_filter to filter out empty and null values. Use array_unique and define a custom comparison function that treats null and null values as equal. Use array_reduce to iterate over an array and add items if they do not contain empty or null values.
Tips for handling empty values and null values when deduplicating PHP arrays
Question
When clearing duplicates in an array, you need to consider how to handle empty and null values. By default, empty strings and null values are treated as different values, which can lead to unexpected duplicates.
Tips
Three common techniques for handling empty and null values:
array_unique
Function collocationarray_filter
Function:$arr = ['red', 'blue', 'green', null, '', 'red']; $filtered_arr = array_filter($arr); $result = array_unique($filtered_arr);
array_unique
function and define a custom comparison function: $arr = ['red', 'blue', 'green', null, '', 'red']; function cmp($a, $b) { return $a === $b; } $result = array_unique($arr, SORT_REGULAR, 'cmp');
array_reduce
function: $arr = ['red', 'blue', 'green', null, '', 'red']; $result = array_reduce($arr, function($carry, $item) { if (!in_array($item, $carry) || $item !== '') { $carry[] = $item; } return $carry; }, []);
Actual case
The following example demonstrates using the first technique to filter and deduplicate an array containing empty and null values:
$users = [ ['name' => 'John Doe', 'age' => 30], ['name' => 'Jane Doe', 'age' => 25], ['name' => 'John Doe', 'age' => 30], // 重复项 ['name' => null, 'age' => null], // 空值 ]; $unique_users = array_filter($users); $unique_users = array_unique($unique_users); print_r($unique_users);
Output:
Array ( [0] => Array ( [name] => John Doe [age] => 30 ) [1] => Array ( [name] => Jane Doe [age] => 25 ) )
The above is the detailed content of Tips for handling empty values and null values when deduplicating PHP arrays. For more information, please follow other related articles on the PHP Chinese website!