Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

4.22. Removing Duplicate Elements from an Array

Problem

You want to eliminate duplicates from an array.

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;
}

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( ).

See Also

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata