PHP Arrays
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 ($_GET['fruits'] as $fruit) {
if (!in_array($fruit, $array)) { $array[] = $fruit; }
}
Here’s one for associative arrays:
foreach ($_GET['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().
No comments:
Post a Comment