Friedrich Siever Friedrich Siever - 1 month ago 9
PHP Question

While loop without explicit increment / counter (basic)

I am new to php and it's my first language. So my question seems to be very basic.

First the basic concept of a while loop seems pretty clear to me.
As long as i increment (i++) until the "crash condition" (i<10) becomes true.

But I realy wonder why the following code example without any explicit incrementation works.

$originals = "originale";
$thumbnails="thumbnails";
$directory = opendir($originale);
$images = array();
while(($file = readdir($directory)) !== false) {
if(preg_match("/\.jp?g$/i", $file)){
$images[] = $file;
}
}
echo "<pre>";
var_dump($images);
echo "</pre>";
closedir($directory);


Obviously I missed something. It seems to be magic. I would expect an enless loop which returns the first file... ?

I hope that despite my English (sorry for that) the question becomes clear.
Many thanks in advance.

Answer

As you can see in the PHP documentation readdir does:

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.

So everytime you call readdir will return the next file from that directory.

For example if you have a direcotry with 2 files:

  • one.txt
  • two.txt

First time you call readdir will return one.txt. And this is different from false so will execute the code inside the while

Second time you call readdir will return two.txt and the same as above.

Thrid time you call readdir will return false because no more files are in that dirrecotry. and the condition from while will not be true anymore so will not enter while anymore.

Comments