Remove duplicates in foreach

I work with my code that displays all folders and subfolders in my directory.

I have a simple problem. Some results are repeated or repeated, and I do not want to display them.

How can i do this?

<?php
    $dir = 'apps/';
    $result = array();

    if (is_dir($dir)) {
            $iterator = new RecursiveDirectoryIterator($dir);
            foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {                    
                if (!$file->isFile()) {
                    $result = $file->getPath()."<br>";
                    echo $result;
                }
            }
    }
?>
+4
source share
3 answers

try it

<?php
    $dir = 'apps/';
    $result = array();

    if (is_dir($dir)) {
            $iterator = new RecursiveDirectoryIterator($dir);
            foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {                    
                if (!$file->isFile()) {
                    $path = $file->getPath();
                    if(in_array($path, $result))  {
                        continue ;
                    }
                    $result = $path."<br>";
                    echo $result;
                }
            }
    }
?>
+1
source

You can use the hash array to check if the path is already in the list

<?php
    $dir = 'apps/';
    $result = array();
    $hash=array();

    if (is_dir($dir)) {
            $iterator = new RecursiveDirectoryIterator($dir);
            foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {                    
                if (!$file->isFile()) {
                    $path = $file->getPath();
                    if(isset($hash[$path]))  {
                        continue ;
                    }
                     $hash[$path]=1;
                    $result[] = $path;
                    echo $path."<br>";
                }
            }
    }
?>
0
source

use array_unique()

<?php

$dir = 'apps/';
$result = array();

if(is_dir($dir)){

    $iterator = new RecursiveDirectoryIterator($dir);
    foreach(new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file){
        if(!$file->isFile()){
            $result[] = $file->getPath();
        }
    }

    $uniqueResult = array_unique($result);
    if(!empty($uniqueResult)){
        foreach($uniqueResult as $v){ // don't use 'for' use 'foreach' here.
            echo $v.'<br>';
        }
    }

}
0
source

Source: https://habr.com/ru/post/1568434/


All Articles