We all know that,PHP function array_flip () format:
- 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:
- $Arr=Array(............) ; // Assume that an array with 10 thousand elements contains repeated elements.
- $Arr=Array_flip(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:
- $Arr1=Array("Age" =>30, "name" =>"Php self-learning network ");
- $Arr2=Array_flip($ Arr1); // $ arr2 is array (30=>"Age", "php self-learning network" =>"Name ");
In the PHP array, different elements can take the same value, but the same key name cannot be used by different elements, such:
- $Arr1=Array("Age" =>30, "name" =>"Php self-learning network", "age" =>20); "age" =>20 will replace "age" =>30
- $Arr1=Array("Name" =>"Php self-learning network", "age" =>45 );
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:
- $Arr1=Array("Age" =>30, "name" =>"Php self-learning network", "age" =>20 );
- $Arr1=Array_flip($ Arr1); // $ arr1 is converted to array ("php self-learning network" =>"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:
- $arr1 = array_flip(array_flip($arr1));