Home > Article > Backend Development > What is the way to remove duplicate values in an array in php
php method to delete duplicate values in an array: Use the [array_unique()] function to delete duplicate elements in the array, sort the values of the array elements as strings, and then retain only the first key name for each value , ignoring all subsequent key names, is to delete duplicate elements in the array.
The operating environment of this tutorial: Windows 7 system, PHP version 5.6, DELL G3 computer. This method is suitable for all brands of computers.
php method to delete duplicate values in the array:
Delete 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, ignoring all subsequent key names, which is to delete the array For repeated elements in
, the syntax format is as follows:
array arry_unique(array array)
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); //输出删除后的数组 ?>
The output result is:
array_unique()
The function only applies to one-dimensional arrays, not multi-dimensional arrays. However, you can use array_unique() for 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); ?>
The output result is:
Related video recommendations: PHP programming from entry to proficiency
The above is the detailed content of What is the way to remove duplicate values in an array in php. For more information, please follow other related articles on the PHP Chinese website!