Remove duplicates of specific string or number in PHP array

WBOY
Release: 2024-04-28 12:57:01
Original
757 people have browsed it

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.

去除 PHP 数组中特定字符串或数字的重复项

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!