简体   繁体   中英

PHP: Better way to filter out duplicates?

I have an array sort of like this.

$images = array
(
    array('src' => 'a.jpg'),
    array('src' => 'b.jpg'),
    array('src' => 'c.jpg'),
    array('src' => 'd.jpg'),
    array('src' => 'b.jpg'),
    array('src' => 'c.jpg'),
    array('src' => 'b.jpg'),
);

There is also height and width, but not important here. What I want is to remove the duplicates. What I have done feels rather clunky.

$filtered = array();
foreach($images as $image)
{
    $filtered[$image['src']] = $image;
}
$images = array_values($filtered);

Is there a better way to do this? Any advice?

This would probably be a good use case for array_reduce

$images = array_values(array_reduce($images, function($acc, $curr){
    $acc[$curr['src']] = $curr;
    return $acc;
}, array()));

Sometimes I use

$filtered = array_flip(array_flip($images))

You have to understand array_flip's behavior though or you might get unexpected results. Some things to note are:

  1. This will remove duplicate values
  2. It removes NULL values
  3. It preserves keys, however, it retains the last duplicate value (not the first)
  4. A function would need to be written to handle multidimensional arrays

Use array_unique .

$images = array_unique($images);

How are you building the array? Possibly keep it from ever being added using...

if(!in_array($needle, $haystackarray)){
    AddToArray;
}

Just a thought.

Use PHP's array_unique() .

Code:

$filtered = array_unique($images);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM