Home  >  Article  >  Backend Development  >  Tips for handling empty values ​​and null values ​​when deduplicating PHP arrays

Tips for handling empty values ​​and null values ​​when deduplicating PHP arrays

王林
王林Original
2024-04-26 17:03:01330browse

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.

PHP 数组去重时处理空值和 null 值的技巧

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:

  1. Use array_uniqueFunction collocationarray_filterFunction:
$arr = ['red', 'blue', 'green', null, '', 'red'];

$filtered_arr = array_filter($arr);
$result = array_unique($filtered_arr);
  1. Use the 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');
  1. Use 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn