Home  >  Article  >  Backend Development  >  How to remove duplicate elements from array in PHP

How to remove duplicate elements from array in PHP

青灯夜游
青灯夜游Original
2019-03-02 16:58:4710942browse

In PHP, you can use the built-in function "array_unique()" to directly delete duplicate elements, or you can use the "array_flip()" function to indirectly delete duplicate elements.

How to remove duplicate elements from array in PHP

【Video tutorial recommendation: PHP tutorial

array_unique() function

array_unique() function can remove duplicate values ​​​​in the array and return the result array; when the values ​​​​of several array elements are equal, only the first element is retained, and the other elements are delete.

Code example:

<?php
$result1 = array("a" => "green", "red", "b" => "green", "blue", "red");
var_dump($result1);
$result2 = array_unique($result1);
var_dump($result2);
?>

Output:

How to remove duplicate elements from array in PHP

##array_flip() function

array_flip() is a function that reverses the keys and values ​​of an array. It has a characteristic that if two values ​​​​in the array are the same, then the last key and value will be retained after the reversal. Use We use this feature to indirectly implement array deduplication.

<?php
header("content-type:text/html;charset=utf-8");
$a = array(1, 5, 2, 5, 1, 3, 2, 4, 5);
// 输出原始数组
echo "原始数组 :";
var_dump($a);
// 通过使用翻转键和值移除重复值
$a = array_flip($a);
// 通过再次翻转键和值来恢复数组元素
$a = array_flip($a);
// 重新排序数组键
$a = array_values($a);
// 输出更新后的数组
echo "更新数组 :";
var_dump($a);
?>

Output:


How to remove duplicate elements from array in PHP

The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to remove duplicate elements from array in PHP. 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