PHP’s array_unique() function is used to remove duplicate elements from an array, and its default use is strict equality (===). We can specify the basis for deduplication through a custom comparison function: create a custom comparison function and specify the deduplication standard (for example, based on element length); pass the custom comparison function as the third parameter to the array_unique() function. Remove duplicate elements based on specified criteria.
Use the PHP array_unique() function to specify the basis for deduplication
Introduction
_unique()
Function is used to remove duplicate elements from an array. By default, it uses strict equality (===
) to determine duplicate elements. However, we can remove duplicate elements based on different criteria by providing a custom comparison function to specify the basis for deduplication.
Code example
<?php // 创建一个包含重复元素的数组 $arr = array( 'a', 'b', 'c', 'd', 'a', 'c', 'e', 'f' ); // 使用默认的严格相等比较器去除重复元素 print_r(array_unique($arr)); // 自定比较器,根据元素长度去除重复元素 $length_comparator = function($a, $b) { return strlen($a) == strlen($b); }; // 使用自定比较器去除重复元素 print_r(array_unique($arr, SORT_REGULAR, $length_comparator)); ?>
Output result
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f ) Array ( [0] => a [1] => b [2] => c [4] => d [6] => e )
Actual case
Suppose we have an array of student objects, each object has a name and age. We can use the _unique()
function and a custom comparator to remove students with the same age:
<?php class Student { public $name; public $age; } // 创建一个包含具有相同年龄的学生对象的数组 $students = array( new Student('Alice', 20), new Student('Bob', 20), new Student('Carol', 21), new Student('Dave', 21), ); // 自定比较器,根据学生的年龄去除重复元素 $age_comparator = function($a, $b) { return $a->age == $b->age; }; // 使用自定比较器去除重复元素 $unique_students = array_unique($students, SORT_REGULAR, $age_comparator); // 打印唯一学生的姓名 foreach ($unique_students as $student) { echo $student->name . '<br>'; } ?>
Output result
Alice Carol
The above is the detailed content of Specify the basis for removing duplicate elements when deduplicating PHP arrays. For more information, please follow other related articles on the PHP Chinese website!