PHP array de-duplication and php array implementation in a faster way. PHP array deduplication in a faster way. Original article: FasterAlternativetoPHPsArrayUniqueFunction overview using php's array_unique () function allows you to pass a faster way to implement de-duplication of PHP arrays and php arrays
Original article: Faster Alternative to PHP's Array Unique Function
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: Use array_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 );
Conclusion
It is very simple. compared to using the array_unique function in a large array, it has an effective performance improvement.
Original article: Faster Alternative to PHPs Array Unique Function overview use the array_unique () Function of PHP to allow you to pass...