Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.