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

How to remove duplicate elements in PHP array

黄舟
Release: 2023-03-07 11:48:02
Original
2315 people have browsed it

Our last article talked about "How to delete the head, tail, and any element in a PHP array". In this article, we talk about deleting duplicate elements in the array through the array_unique() function.

array_unique() function sorts the values ​​of the array elements as strings, and then only retains the first key name for each value and ignores all subsequent key names, which is to delete duplicate elements in the array,

The syntax format is as follows:

array arry_unique(array array)
Copy after login

The parameter array is the input array.

The following example uses the array_unique() function to delete duplicate elements in the array. The specific example code is as follows:

<?php
header("Content-Type:text/html; charset=utf-8");
$array_push = array("PHP中文网","www.php.cn", "www.php.cn", "PHP 从入门到精通");//定义数组
array_push($array_push,"百度一下","www.php.cn");//添加元素
print_r($array_push);
echo "<br>";
$result=array_unique($array_push);//删除数组中重复的元素
print_r($result); //输出删除后的数组
?>
Copy after login

The output result is:

How to remove duplicate elements in PHP array

## The #array_unique() function only applies to one-dimensional arrays, not multi-dimensional arrays. However, you can use array_unique() to add values ​​in a two-dimensional array.

The following example uses the array_unique() function to delete duplicate elements of a two-dimensional array. The specific code is as follows:,

<?php
$array = array(array(1,1,2),array(2,3,4,3));
print_r($array);
$temp_array = array();
foreach($array as $key=>$value){
    $temp_array[$key] = array_unique($value);
}
$array = $temp_array;
echo "<br>";
print_r($array);
?>
Copy after login
The output result is:

How to remove duplicate elements in PHP array

【Related tutorial recommendations】

1. Relevant topic recommendations: "

php array (Array)"

2. Related videos Course recommendation: "

Array statistical functions: count(), array_count_values() and array_unique()"


The above is the detailed content of How to remove duplicate elements in PHP array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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