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

王林
Release: 2024-04-26 17:03:01
Original
384 people have browsed it

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);
Copy after login
  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');
Copy after login
  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;
}, []);
Copy after login

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);
Copy after login

Output:

Array
(
    [0] => Array
        (
            [name] => John Doe
            [age] => 30
        )
    [1] => Array
        (
            [name] => Jane Doe
            [age] => 25
        )
)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template