Home  >  Article  >  Backend Development  >  How to remove duplicate elements from PHP array using foreach loop?

How to remove duplicate elements from PHP array using foreach loop?

PHPz
PHPzOriginal
2024-04-27 11:33:01773browse

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.

如何使用 foreach 循环去除 PHP 数组中的重复元素?

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!

Statement:
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