The method is as follows:
| The code is as follows: |
Copy code |
|
$ Arr = array (............) ; // Assume that an array contains 10 thousand elements with 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 (): array_flip () is used to exchange the keys and values of each element of an array, for example:
| The code is as follows: |
Copy code |
|
$ Arr1 = array ("age" => 30, "name" => 'kuaiyun ');
$ Arr2 = array_flip ($ arr1); // $ arr2 is an array (30 => "age", 'paradise '=> "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: |
Copy code |
|
$ Arr1 = array ("age" => 30, "name" => 'kuaiyun', "age" => 20 ); "age" => 2 0 will replace "age" => 30
$ Arr1 = array ("name" => 'Happy paradise ', "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:
| The code is as follows: |
Copy code |
|
$ Arr1 = array ("age" => 30, "name" => 'kuaiyun', "age" => 20 );
$ Arr1 = array_flip ($ arr1); // $ arr1 is converted to array ("Fast Park" => "name", 20 => "age ");
// Restore the key name and value of $ arr1:
$ Arr1 = array_flip ($ arr1 ); |
The code above is concise: $ arr1 = array_flip ($ arr1 ));
Some custom functions
// Delete the function of repeating elements in the array
| The code is as follows: |
Copy code |
Function delmember (& $ array, $ id)
{
$ Size = count ($ array );
For ($ I = 0; $ I <$ size-$ id-1; $ I ++)
{
$ Array [$ id + $ I] = $ array [$ id + $ I + 1];
}
Unset ($ array [$ size-1]);
}
|
// Example:
| The code is as follows: |
Copy code |
|
$ Output = array (1, 2, 2, 'www .111cn.net ', 5, 4, 4, 4, 2, 7, 5, 9, 10 );
Delsame ($ output );
While (list ($ key, $ value) = each ($ output ))
{
Echo "$ key: $ value". "<br> ";
}
// Method 2
Function uniquearray ($ array)
{
// Get unique elts as keys in assoc. array
For ($ I = 0, $ n = count ($ array, 1); $ I <$ n; $ I)
$ U_array [$ array [$ I] = 1;
// Copy keys only into another array
Reset ($ u_array, 1 );
For ($ I = 0, $ n = count ($ u_array, 1); $ I <$ n; $ I ){
$ Unduplicated_array [] = key ($ u_array, 1 );
Next ($ u_array, 1 );
}
Return $ unduplicated_array;
} |