Role of the PHP function array_flip () in deleting repeated array elements

Source: Internet
Author: User

We all know that,PHP function array_flip () format:

 
 
  1. 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:

 
 
  1. $Arr=Array(............) ; // Assume that an array with 10 thousand elements contains repeated elements.
  2. $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:

 
 
  1. $Arr1=Array("Age" =>30, "name" =>"Php self-learning network ");
  2. $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:

 
 
  1. $Arr1=Array("Age" =>30, "name" =>"Php self-learning network", "age" =>20); "age" =>20 will replace "age" =>30
  2. $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:

 
 
  1. $Arr1=Array("Age" =>30, "name" =>"Php self-learning network", "age" =>20 );
  2. $Arr1=Array_flip($ Arr1); // $ arr1 is converted to array ("php self-learning network" =>"Name ",20=>"Age ");
  3. // Restore the key name and value of $ arr1:
  4. $Arr1=Array_flip($ Arr1 );

The code of the above PHP function array_flip () is concise:

 
 
  1. $arr1 = array_flip(array_flip($arr1));   


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.