PHP programming quick array de-duplication method explanation, php programming array explanation
This example describes how to quickly implement array deduplication using PHP programming. We will share this with you for your reference. The details are as follows:
Overview
PHParray_unique()
The function allows you to pass an array, remove duplicate values, and return an array with unique values. This function works well in most cases. However, if you try to usearray_unique()
Function, which runs slowly.
There is a better and faster Functionarray_flip()
To replacearray_unique()
Function to create a unique array. This magic function exchanges the keys and values of each element in the array. Because the key values must be uniquearray_unique()
Returns the same result as a function.
Faster PHP array deduplication
/* Create an array containing repeated values and a total of four elements */$ array = array ('green', 'Blue ', 'Orange', 'Blue '); /* flip the array and you will get the array ('green' => 0, 'Blue '=> 1, 'Orange' => 2) with the unique key value ); */$ array = array_flip ($ array);/* flip it again, place the key and value again, and obtain the array: array (0 => 'green ', 1 => 'blue', 2 => 'Orange '); */$ array = array_flip ($ array );
Because we have removed some elements, the array does not look like a normal sequence. For example, we may get:
array(0=>'A',2=>'B',5=>'C');
In some cases, this is not a problem, but if you need the array key value to keep the sequence of numbers, you can use one or two methods to solve the key value disorder.
Use array_merge to fix the array keys
The function after array_flip is added will sort the key values of the array and restore them to a normal sequence, for example, 0, 1, 2, 3...
$ Array = array ('green', 'Blue ', 'Orange', 'Blue '); $ array = array_flip ($ array ); /* use the array_merge () function to fix the key value */$ array = array_merge ($ array );
Method 2: Usearray_keys
Note that this method is betterarray_merge()
The function is a little faster. You can also use it in the last step.array_keys()
Function (this function returns the value after the flip ). Then, when you flip the value of the array, the key value will be created in order.
$ Array = array ('green', 'Blue ', 'Orange', 'Blue '); $ array = array_flip ($ array);/* same as the first example, but now we extract the key value of the array */$ array = array_keys ($ array );
PS: There are two simple and practical online text deduplication tools on this site. We recommend this tool to you:
Online deduplication tools:
Http://tools.jb51.net/code/quchong
Online text deduplication tool:
Http://tools.jb51.net/aideddesign/txt_quchong