Home >Backend Development >PHP Tutorial >How to remove duplicate elements from PHP array using foreach loop?
The method of using foreach loop to remove duplicate elements in PHP array is as follows: traverse the array, if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.
How to remove duplicate elements from a PHP array using foreach loop?
PHP's array_unique
function can be used to remove duplicate elements from an array, but sometimes you may want to do this manually using a foreach loop. Here's how to achieve this using a foreach loop:
<?php // 创建一个包含重复元素的数组 $array = array(1, 2, 3, 4, 5, 1, 2, 3); // 使用 foreach 循环遍历数组 foreach ($array as $key => $value) { // 如果数组中已经存在该值,则删除它 if (array_key_exists($value, $array) && $key !== array_key_first($array)) { unset($array[$key]); } } // 输出去除重复元素后的数组 print_r($array); ?>
Practical example: Remove duplicate values from database query results
Suppose you have a query database and return the following results PHP script:
$results = [ ['id' => 1, 'name' => 'John'], ['id' => 2, 'name' => 'Mary'], ['id' => 1, 'name' => 'John'], // 重复的记录 ['id' => 3, 'name' => 'Bob'], ];
You can use the above foreach loop to remove duplicate values and get the following result:
$uniqueResults = [ ['id' => 1, 'name' => 'John'], ['id' => 2, 'name' => 'Mary'], ['id' => 3, 'name' => 'Bob'], ];
The above is the detailed content of How to remove duplicate elements from PHP array using foreach loop?. For more information, please follow other related articles on the PHP Chinese website!