Break WHILE with readdir

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
Pazuzu156
Forum Contributor
Posts: 241
Joined: Sat Nov 20, 2010 9:00 pm
Location: GA, USA
Contact:

Break WHILE with readdir

Post by Pazuzu156 »

I have an image directory for user images. And when they want to change pictures, it shows the 4 most recent ones. How do I limit this with my code:

Code: Select all

<?php
$imgDir = "./ppics/".$fname.$lname;
$handler = opendir($imgDir);
$ignore = array('.','..','Thumbs.db');
while($file = readdir($handler)) {
	if(!in_array($file,$ignore)) {
		echo '<a href="./assets/changePic.php?img='.$file.'" name="pic_'.$file.'"><img src="'.$imgDir.'/'.$file.'" alt="image_'.$file.'" style="width:50px;"></a> ';
	}
}
?>
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Break WHILE with readdir

Post by social_experiment »

If i understand correctly you only want to show 1 image: adding break might do it

Code: Select all

<?php
if(!in_array($file,$ignore)) {
                echo '<a href="./assets/changePic.php?img='.$file.'" name="pic_'.$file.'"><img src="'.$imgDir.'/'.$file.'" alt="image_'.$file.'" style="width:50px;"></a> ';
        }
// add a break statement
break;
?>
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Pazuzu156
Forum Contributor
Posts: 241
Joined: Sat Nov 20, 2010 9:00 pm
Location: GA, USA
Contact:

Re: Break WHILE with readdir

Post by Pazuzu156 »

I want to show 5, then break.
- Kaleb Klein
------------------------------------
Web Developer | Software Developer
https://kalebklein.com
PGP Key: https://keybase.io/pazuzu156
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Break WHILE with readdir

Post by pickle »

Add a counter. break when the counter reaches 5.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply