PHP is a popular programming language, and its powerful array processing capabilities are one of the important reasons why it is highly praised. In PHP programming, we often need to perform array operations. One of the common operations is to delete a specific value in the array. This article will explain how to delete identical values in an array in PHP.
In PHP, we can delete a specific key-value pair in the array through the unset() function. However, if we need to delete multiple elements with the same value in the array, this method becomes a bit cumbersome. In order to more conveniently delete duplicate elements in an array, PHP provides a built-in function array_unique().
The array_unique() function is to return a new array that only contains values that are not repeated in the original array. This function can be used through the following code:
<?php $arr = array("PHP", "Java", "Python", "PHP", "C++", "Ruby", "C#"); $new_arr = array_unique($arr); print_r($new_arr); ?>
The output of the above code is:
Array ( [0] => PHP [1] => Java [2] => Python [4] => C++ [5] => Ruby [6] => C# )
As you can see, we successfully deleted the duplicate elements in the original array.
However, the above code only demonstrates how to remove duplicate values through the array_unique() function. What if we need to delete duplicate elements directly in the original array? At this time, we can combine the array_unique() function and the array_diff() function to delete duplicate elements in the original array.
The array_diff() function is to return the difference between two arrays, that is, return the value that array 1 has but array 2 does not. We can use this difference to calculate the duplicate elements in the original array and delete them from the original array. The specific idea can be realized through the following code:
<?php $arr = array("PHP", "Java", "Python", "PHP", "C++", "Ruby", "C#"); $unique_arr = array_unique($arr); //去重 $duplicate_arr = array_diff_assoc($arr, $unique_arr); //计算重复元素 foreach($duplicate_arr as $key => $val){ //遍历重复元素 while(($index = array_search($val, $arr)) !== false){ //在原数组中依次查找元素位置 unset($arr[$index]); //删除元素 } } print_r($arr); ?>
The execution result of the above code is:
Array ( [1] => Java [2] => Python [4] => C++ [5] => Ruby [6] => C# )
As you can see, we successfully deleted the duplicate elements in the original array and obtained a new array. .
To sum up, the method of deleting the same values in the array can be achieved by combining the array_unique() function and the array_diff() function. Among them, the array_unique() function is used to remove duplicate values, and the array_diff() function is used to calculate duplicate elements. Through the above method, we can more conveniently perform array operations in PHP programming.
The above is the detailed content of How to delete identical values in array in PHP. For more information, please follow other related articles on the PHP Chinese website!