Jump to content

[SOLVED] Help with while loop and file_exists


joosh

Recommended Posts

Hello, everything I've tried can't make this work, so here is what I want in long form:

$filepath = 'img/' . $_POST['anim_name'] . '/' . $_POST['anim_name'] . '-' . $_POST['date'] . '-01.jpg';
if (file_exists($filepath)) {
$filepath = 'img/' . $_POST['anim_name'] . '/' . $_POST['anim_name'] . '-' . $_POST['date'] . '-02.jpg';
if (file_exists($filepath)) {
	$filepath = 'img/' . $_POST['anim_name'] . '/' . $_POST['anim_name'] . '-' . $_POST['date'] . '-03.jpg';
	if (file_exists($filepath)) {
		$filepath = 'img/' . $_POST['anim_name'] . '/' . $_POST['anim_name'] . '-' . $_POST['date'] . '-04.jpg';
		if (file_exists($filepath)) {
			$filepath = 'img/' . $_POST['anim_name'] . '/' . $_POST['anim_name'] . '-' . $_POST['date'] . '-05.jpg';
		}
	}
}
}

Right before the file extension .jpg there is a sequence number (01, 02, etc, must have leading 0).

I want it to increment the sequence number when file_exists() returns false and keep incrementing until it gets to an acceptable file name. I haven't figured out how to make:

while (!file_exists($filename)) work just yet.

Can someone help me out with this?

Thanks a lot,

Josh

Use a for loop.

 

<?php

// define a max
define('MAX_TRIES', 99);

// loop until we find one or we hit the max
for($i=0, $found=false;$i<MAX_TRIES;$i++) {

// format the file path 
$filepath = sprintf('img/%s/%s/%s-%02d.jpg', $_POST['anim_name'],$_POST['anim_name'],$_POST['date'],$int);

// Check to see if it exists
if(file_exists($filepath)) {

	// tell us it did, and set the flag to true
	echo 'File exists!';
	$found = true;
	break;
}
}

// check the glad to see if nothing was found
if(!$found) {
echo 'nothing was found';
}
?>

Works perfectly! Thanks for the quick solution!

I modified it down to this:

$max = 99;
for($i=1,$found=false;$i<$max;$i++) {
$filepath = sprintf('img/%s/%s-%s-%02d.jpg', $_POST['anim_name'],$_POST['anim_name'],$_POST['date'],$i);
if(!file_exists($filepath)) {
	$found = true;
	break;
}
}

In the file_exists statement I had to put the leading ! to make it work. It was stopping at 01.

Thanks a lot! I just stumbled upon sprintf() a minute ago but didn't make a whole lot of sense to me.

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.