This article provides a detailed analysis of the role of the PHP function array_flip () in the deletion of repeated array elements. For more information, see, there are many ways to delete array elements in PHP. commonly used functions include array_unique () in php (). The PHP function array_flip () introduced today is about five times more efficient than the array_unique () function in deleting array repeated elements.
PHP function array_flip () format:
The code is as follows:
Array array_flip (array trans)
// Array_flip -- exchange keys and values in the array
Array array_flip (array trans) // array_flip -- exchange keys and values in the array
The method is as follows:
The code is as follows:
$ Arr = array (............) ; // Assume that an array with 10 thousand elements contains repeated elements.
$ Arr = array_flip ($ arr); // you can delete duplicate elements.
What is going on? Let's take a look at the role of array_flip (): The PHP function array_flip () is used to exchange the keys and values of each element in an array, for example:
The code is as follows:
$ Arr1 = array ("age" => 30, "name" => "");
$ Arr2 = array_flip ($ arr1); // $ arr2 is array (30 => "age", "" => "name ");
In the PHP array, different elements can take the same value, but the same key name cannot be used by different elements, such:
The code is as follows:
$ Arr1 = array ("age" => 30, "name" => "", "age" => 20 ); "age" => 20 will replace "age" => 30
$ Arr1 = array ("name" => "", "age" => 20 );
Here $ arr1 and $ arr2 are equal.
So we can know why array_flip ($ arr) can delete repeated elements in the array. First, the value in $ arr is changed to the key name, because the value is repeated. after the value is changed to the key name, the duplicate values become duplicate key names, the PHP engine deletes duplicate key names and retains only the last one. For example:
The code is as follows:
$ Arr1 = array ("age" => 30, "name" => "", "age" => 20 );
$ Arr1 = array_flip ($ arr1); // $ arr1 becomes an array ("" => "name", 20 => "age ");
// Restore the key name and value of $ arr1:
$ Arr1 = array_flip ($ arr1 );
The code of the above PHP function array_flip () is concise:
The code is as follows:
$ Arr1 = array_flip ($ arr1 ));