Search code examples
phprecursionarray-push

Add data in array recursive php


I have a small problem, I have many directory which contains other directory and files. I would like to get all the directory names using a recursive way I have :

function getNomDossier($dir){
    $root = scandir($dir); //scanne le dossier
    $nom = [];
    foreach ($root as $value) {
        $variable = "$dir/$value";
        if ($value === '.' || $value === '..' || $value === '.DS_Store') {
            continue;
        }
        //on teste si c'est un dossier
        if (is_dir($variable)){
            array_push($nom, $value);
            getNomDossier($variable);

        }
    }

    return $nom;
}

When doing this I only have the first "scan", it doesn't go inside the directory to scan again and push into $nom...

Sorry if it's not clear and thank you for your help


Solution

  • you are checkig if $variable is a directory and then push $value in $nom you just forget to push the value returned by getNomDossier to $nom. so to solve your problem replace:

    getNomDossier($variable); 
    

    with this:

    $nom = array_merge($nom, getNomDossier($variable));
    

    and the code should look like this:

    function getNomDossier($dir){
        $root = scandir($dir); //scanne le dossier
        $nom = [];
        foreach ($root as $value) {
            $variable = "$dir/$value";
            if ($value === '.' || $value === '..' || $value === '.DS_Store') {
                continue;
            }
            //on teste si c'est un dossier
            if (is_dir($variable)){
                array_push($nom, $value);
                $nom = array_merge($nom, getNomDossier($variable));
            }
        }
    
        return $nom;
    }