There are several functions to delete duplicate elements from an array in PHP. One is array_unique() and the other is array_flip() and array_uniqure() functions, but the latter is several times more performant than the former, so I will only introduce the two. to remove duplicate array elements.
The method is as follows:
The code is as follows | Copy code | ||||||||
|
What is going on? Let’s look at the function of array_flip(): array_flip() is used to exchange the key and value of each element of an array, such as:
The code is as follows | Copy code | ||||
$arr1 = array("age" => 30, "name" => 'Happy Garden');
$arr2 = array_flip($arr1); // $arr2 is array(30 => "age", 'Happy Garden' => "name"); |
In a PHP array, different elements are allowed to take the same value, but the same key name is not allowed to be used by different elements, such as:
The code is as follows | Copy code | ||||
$arr1 = array("age" => 30, "name" => 'Happy Garden', "age" => 20); "age" => 2 0 will replace "age" => 30
$arr1 = array("name" => 'Happy Garden', "age" => 45); |
So, we can know why array_flip(array_flip($arr)) can delete duplicate elements in the array. First, the value in $arr will become a key name, because the value is repeated. After becoming a key name, these repeated values will become duplicate key names. The PHP engine will delete the duplicate key names and only keep the last one. . Such as:
代码如下 | 复制代码 |
function delmember(&$array, $id) { $size = count($array); for($i = 0; $i <$size - $id - 1; $i ++) { $array[$id + $i] = $array[$id + $i + 1]; } unset($array[$size - 1]); } |
The code is as follows | Copy code |
<🎜>$arr1 = array("age" => 30, "name" => 'Happy Garden', "age" => 20); $arr1 = array_flip($arr1); // $arr1 becomes array("Happy Garden" => "name", 20 => "age"); //Restore the key name and value of $arr1: $arr1 = array_flip($arr1); |
The code is as follows | Copy code |
function delmember(&$array, $id) { $size = count($array); for($i = 0; $i <$size - $id - 1; $i ++) <🎜> { <🎜> $array[$id + $i] = $array[$id + $i + 1]; <🎜> } <🎜> unset($array[$size - 1]); <🎜> } <🎜> |
//使用例子:
代码如下
| 复制代码 | ||||
function uniquearray($array)
reset($u_array, 1); for ($i=0,$n=count($u_array, 1);$i<$n;$i ) {