Recipe 4.21. Removing Duplicate Elements from an Array


4.21.1. Problem

You want to eliminate duplicates from an array.

4.21.2. Solution

If the array is already complete, use array_unique( ), which returns a new array that contains no duplicate values:

$unique = array_unique($array);

If you create the array while processing results, here is a technique for numerical arrays:

foreach ($_REQUEST['fruits'] as $fruit) {     if (!in_array($array, $fruit)) { $array[] = $fruit; } }

Here's one for associative arrays:

foreach ($_REQUEST['fruits'] as $fruit) {     $array[$fruit] = $fruit; }

4.21.3. Discussion

Once processing is completed, array_unique( ) is the best way to eliminate duplicates. But if you're inside a loop, you can eliminate the duplicate entries from appearing by checking if they're already in the array.

An even faster method than using in_array( ) is to create a hybrid array in which the key and the value for each element are the same. This eliminates the linear check of in_array( ) but still allows you to take advantage of the array family of functions that operate over the values of an array instead of the keys.

In fact, it's faster to use the associative array method and then call array_values( ) on the result (or, for that matter, array_keys( ) , but array_values( ) is slightly faster) than to create a numeric array directly with the overhead of in_array( ).

4.21.4. See Also

Documentation on array_unique( ) at http://www.php.net/array-unique.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net