Home > Article > Backend Development > Remove duplicates of specific string or number in PHP array
How to remove duplicates from a PHP array: The array_unique() function returns a new array in which duplicates have been removed, retaining the first occurring value. The array_filter() function uses a callback function and returns a new array in which elements that meet the conditions of the callback function will be retained, for example, only the unique occurrence of the element will be retained.
How to remove duplicates from an array in PHP
PHP provides a variety of methods to remove duplicates from an array . This article will introduce how to use the array_unique()
function and the array_filter()
function to achieve this purpose.
array_unique()
array_unique()
The function accepts an array as argument and returns a new array in which duplicates have been removed. It retains the first occurrence of the value in the array.
Example:
<?php $arr = ['a', 'b', 'a', 'c', 'd', 'b']; $uniqueArr = array_unique($arr); print_r($uniqueArr); // 输出:Array ( [0] => a [1] => b [2] => c [3] => d ) ?>
array_filter()
array_filter()
The function receives an array and A callback function is taken as a parameter and a new array is returned, in which elements that meet the conditions of the callback function will be retained.
Example:
<?php $arr = ['a', 'b', 'a', 'c', 'd', 'b']; $uniqueArr = array_filter($arr, function ($value) { return count(array_keys($arr, $value)) === 1; }); print_r($uniqueArr); // 输出:Array ( [0] => a [1] => c [2] => d ) ?>
Practical case
The following is a function using array_unique()
Practical case:
<?php // 从数据库中获取用户 ID 的数组 $userIds = [1, 2, 3, 1, 5, 2, 4]; // 去除重复的 user ID $uniqueUserIds = array_unique($userIds); // 返回唯一的 user ID 列表 echo json_encode($uniqueUserIds); ?>
The above is the detailed content of Remove duplicates of specific string or number in PHP array. For more information, please follow other related articles on the PHP Chinese website!