Abigail
Abigail

Reputation: 1

Why does the array_filter function work only for last directory in a loop in PHP?

While looping through various directories, I used array_filter to put the directories' filenames into an array, then we proceed to the next directory;

The value of $HALLO1 is a value that is read from an array.

One thing I noticed is that when array_filter() is operated on $HALLO1 and in the case where $HALLO1 is equal to an array of directories, the var_dump() function does not list files in the first directories but only list the files contained in last directory. However, when $HALLO1 is equal to one and only directory the array_filter() works and lists all the files contained in that directory. Why is that ?

<?php

foreach ($CC1 as $directory)  {
    $GG1 = strval($CC1[$dd]);
    $HALLO1 = $GG1;
    echo "HALLO1 = " . $HALLO1 ;
    $iterator = new DirectoryIterator(dirname($HALLO1));
    //*****************************************************
    $f_files = array_filter(glob("$HALLO1*"), 'is_file');
    var_dump($f_files);
    //*****************************************************
    ++$dd; 
    } 

?>

Upvotes: 0

Views: 428

Answers (1)

Mark Baker
Mark Baker

Reputation: 212452

Because you're overwriting $f_files in each iteration

$f_files = array()
foreach ($CC1 as $directory)  {
    $GG1 = strval($CC1[$dd]);
    $HALLO1 = $GG1;
    $f_files = array_merge($f_files, array_filter(glob("$HALLO1*"), 'is_file'));
}
var_dump($f_files);

Upvotes: 1

Related Questions