Can't understand a piece of code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
wendyj
Forum Newbie
Posts: 12
Joined: Fri Aug 01, 2014 3:14 am
Location: South Africa

Can't understand a piece of code

Post by wendyj »

I am having trouble understanding how a part in this 'while' piece of code works. I hope that i have given enough of the code to make sense.

I understand that while currentFile is false (or still has more files to go through in the directory) that the code will keep going - So, currentFile lands up holding all the info for the directory, and is then broken up into an array using $theFiles[]?

If i add a foreach, will it show all theFiles (obviously it is set to display image files, but the file names can be shown just to see if it is working); what will this foreach piece of code look like - I have tried to create one but it didn't work:

Code: Select all

foreach($theFiles as $testFiles){
print $testFiles;

}



Code: Select all

...

$dirName = "images/";
$dp = opendir($dirName);

chdir($dirName);

//add all files in directory to $theFiles array
while ($currentFile !== false){
$currentFile = readDir($dp);
$theFiles[] = $currentFile;
} // end while

//extract gif and jpg images
$imageFiles = preg_grep("/jpg$|gif$/", $theFiles);

...
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Can't understand a piece of code

Post by Celauran »

wendyj wrote:So, currentFile lands up holding all the info for the directory, and is then broken up into an array using $theFiles[]?
Close, but not quite. readdir() returns either the next entry in the open directory, or false if there are no more entries. $currentFile holds just that -- the most recent file returned by readdir(). This variable is overwritten on each iteration. The contents of $currentFile are then appended to $theFiles before the loop ends. Based on the code I can see, your foreach loop should work fine. When you say it isn't working, what specifically is happening?
User avatar
wendyj
Forum Newbie
Posts: 12
Joined: Fri Aug 01, 2014 3:14 am
Location: South Africa

Re: Can't understand a piece of code

Post by wendyj »

The piece of code above works, i was making my own code to practice this technique - my piece of code was doing what you explained above, it was only showing one entry!
Post Reply