Jump to content

php don't stop executing after $i < 3


Sun_Blood

Recommended Posts

I'm tired and want to sleep so my mistakes are getting lots now. Anybody awake that can explain my problem with the code below.  :confused:

 

<?

function directoryToArray($directory, $recursive) {
        $array_items = array();
        $i = "0";
        if ($handle = opendir($directory)) {
                while (false !== ($file = readdir($handle)) && $i < "3") {
                        if ($file != "." && $file != "..") {
                                if (is_dir($directory. "/" . $file)) {
                                        if($recursive) {
                                                $array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive));
                                        }
                        } else {
                                        $file = $directory . "/" . $file;
                                        $array_items[] = preg_replace("/\/\//si", "/", $file);
                                        $i++;
                                }
                        }
                }
                closedir($handle);
        }
        natsort($array_items);
        return array_reverse($array_items);
}
$data = directoryToArray('images/screenshot/', TRUE);
print_r($data);
?>

 

What I want is for the while loop to stop after 4 hits and exit and give me the return results. But now it continue until readdir end.

Link to comment
https://forums.phpfreaks.com/topic/211328-php-dont-stop-executing-after-i-3/
Share on other sites

Make $i static so it retains its value in the recursive calls:

 

 static $i = 0;

 

Depending upon how you use it that may cause problems, not sure.  So you should probably pass in $i like so:

 

function directoryToArray($directory, $recursive, $i=0) {

 

Then remove:

 

static $i = 0;

 

Then in the recursive call do:

 

$array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive, $i));

The static trick worked but not the other one.

 

If I do that I get 5 hits and not 4 and if I lower i=3 then i get 3 hits so some hidden file get counted as 1.

Where did you plan to put the $i++ in your second example?

 

Sorry I must sleep now. Hope I can fix all this tomorrow with a fresh brain :)

Thanks for all the suggestions!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.