Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate values from array in foreach loop?

I want to remove duplicate values from array. I know to use array_unique(array) function but faced problem in foreach loop. This is not a duplicate question because I have read several questions regarding this and most of them force to use array_unique(array) function but I have no idea to use it in foreach loop. Here is my php function.

$images = scandir($dir);
$listImages=array();
foreach($images as $image){
    $listImages=$image;
    echo substr($listImages, 0, -25) ."<br>"; //remove last 25 chracters
}

How to do this?

like image 361
Bandara Avatar asked Apr 22 '26 17:04

Bandara


2 Answers

It is very complicated to remove duplicate values from array within foreach loop. Simply you can push all elements to one array and then remove the duplicates and then get values as you need. Try with following code.

   $listImages=array();
   $images = scandir($dir);

   foreach($images as $image){
       $editedImage = substr($image, 0, -25);
       array_push($listImages, $editedImage);
   } 

   $filteredList = array_unique($listImages);

   foreach($filteredList as $oneitem){
       echo $oneitem;
   }
like image 184
isuru Avatar answered Apr 25 '26 06:04

isuru


The example you provided could be modified as follows:

$images = scandir($dir);
$listImages=array();
foreach($images as $image) {
    if (!in_array($image, $listImages)) {
        $listImages[] = $image;
    }
    echo substr($image, 0, -25) ."<br>"; //remove last 25 chracters
}

Now $listImages will contain no duplicates, and it will echo every image (including duplicates).

like image 27
mister martin Avatar answered Apr 25 '26 08:04

mister martin