Friedrich Siever Friedrich Siever - 1 year ago 64
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";
$directory = opendir($originale);
$images = array();
while(($file = readdir($directory)) !== false) {
if(preg_match("/\.jp?g$/i", $file)){
$images[] = $file;
echo "<pre>";
echo "</pre>";

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download