4.23.1 Problem
4.23.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);
foreach ($_REQUEST['fruits'] as $fruit) {
if (!in_array($array, $fruit)) { $array[ ] = $fruit; }
}
foreach ($_REQUEST['fruits'] as $fruit) {
$array[$fruit] = $fruit;
}
4.23.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.