Php array deduplication for array elements _ PHP Tutorial

Source: Internet
Author: User
Php array de-duplicates array elements. The simplest method is to use the built-in functions of php to implement de-duplication with array_flip, another method is to use the array_flip function of php to indirectly implement de-duplication. array_flip is the easiest way to reverse the array key and value. The built-in function of php uses array_flip to achieve de-duplication, another method is to use the array_flip function of php to indirectly implement deduplication.

Array_flip is a function that reverses the array key and value. it has a feature that if two values in the array are the same, the last key and value will be retained after the inversion.

Value. We use this feature to indirectly implement array deduplication.

The code is as follows:

$ Arr = array ("a" => "a1", "B" => 'b1 ', "c" => "a2 ", "d" => "a1 ");
$ Arr1 = array_flip ($ arr );
Print_r ($ arr1); // first reverse the expression, remove the duplicate value, and output Array ([a1] => d [b1] => B [a2] => c)
$ Arr2 = array_flip ($ arr );
Print_r ($ arr2); // returns the array after deduplication, output Array ([a1] => d [b1] => B [a2] => c)
$ Arr3 = array_unique ($ arr );
Print_r ($ arr3); // use the array_unique function of php to deduplicate and output Array ([a] => a1 [B] => b1 [c] => a2)
?>

User-defined function operations

The code is as follows:

Function assoc_unique ($ arr, $ key ){
$ Tmp_arr = array ();
Foreach ($ arr as $ k =>$ v ){
If (in_array ($ v [$ key], $ tmp_arr )){
Unset ($ arr [$ k]);
} Else {
$ Tmp_arr [] = $ v [$ key];
}
}
Sort ($ arr );
Return $ arr;
}

$ Aa = array (
Array ('id' => 123, 'name' => 'faint fragrance filled the world '),
Array ('id' => 123, 'name' => 'crab '),
Array ('id' => 124, 'name' => 'front-end developer '),
Array ('id' => 125, 'name' => 'crab '),
Array ('id' => 126, 'name' => 'html5 investigator ')
);
$ Key = 'name ';
Assoc_unique (& $ aa, $ key );
Print_r ($ aa );
?>

Array_flip is used to reverse the array key and value...

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.