Resolves the role of the PHP function array_flip of in deleting duplicate array elements

  • 2020-06-22 23:57:02
  • OfStack

As we all know, there are many ways to delete array elements in PHP, including array_unique() in php. The PHP function, array_flip(), is about five times more efficient at removing duplicate elements from an array than the array_unique() function.
PHP function array_flip() format:


array array_flip ( array trans ) 
//array_flip --  Swap keys and values in an array 

array array_flip (array trans) //array_flip -- Swap keys and values in an array
The methods are as follows:

$arr = array( ..................... ) ;// Suppose you have 1 An array of ten thousand elements with duplicate elements.    
$arr = array_flip(array_flip($arr)); // This removes duplicate elements. 

What's going on? The PHP function array_flip() is used to exchange keys and values for each element of an array, such as:

$arr1 = array ("age" => 30, "name" => " The home of the script ");   
$arr2 = array_flip($arr1); //$arr2  is  array(30 => "age", " The home of the script " => "name");

In PHP arrays, different elements are allowed to have the same value, but the same key name is not allowed to be used by different elements, such as:

$arr1 = array ("age" => 30, "name" => " The home of the script ", "age" => 20); "age" => 20 Will replace "age" => 30   
$arr1 = array ("name" => " The home of the script ", "age" => 20);  

Here $arr1 is equal to $arr2.
We can then see why array_flip(array_flip($arr)) can remove duplicate elements from an array. First of all, the value in $arr becomes the key name because the value is duplicate. After the value becomes the duplicate key name, the PHP engine removes the duplicate key name, leaving only the last one. Such as:

$arr1 = array ("age" => 30, "name" => " The home of the script ", "age" => 20);   
$arr1 = array_flip($arr1); //$arr1  Turned out to be  array(" The home of the script " => "name", 20 => "age");   
// Then put the  $arr1  The key name and value of    
$arr1 = array_flip($arr1); 

The above PHP function array_flip() is written in the following code:

$arr1 = array_flip(array_flip($arr1));


Related articles: