I have some files i want to upload. And when i upload them, i want the first to be numbered 00, the second to be numbered 01. I wrote a function to get the newest number, but of course, this ain't workin
$i = 00;
while($i < $filecount)
{
if(!file_exists("../photo/$i.jpg"))
开发者_开发问答 {
return $i;
print($i);
}
else if(file_exists("../photo/$i.jpg")) {
$i = $i + 01;
}
But now, when i upload a file, it just numbers it: 0, 1, 2, 3.
I got some new code :
function getFileNumber() {
$i = 0;
while ($i < $filecount) {
$fn = sprintf("../photo/%02d.jpg", $i);
if (!file_exists($fn)) {
return $i;
} else {
$i ++;
}
}
}
But it returns 00 every time, but i want to to go 00,01,02,03. Somebody any ideas?
Integer literals don't contain any formatting. 1
is the value one, it can't be "01", that's a formatting problem. As such, format your numbers:
$file = sprintf('%2u.jpg', $i);
You can use
echo str_pad($i, 2, "0", STR_PAD_LEFT);
Additionally, your print() after the return will never be executed and use if/else instead of if/elseif.
Check out sprintf() that allows for pretty flexible string formatting - especially check out the padding and width specifiers. You're looking for something along the lines of
$i = 0;
while ($i < $filecount)
{
$fn = sprintf("../photo/%02d.jpg", $i);
if (!file_exists($fn))
{
return $i;
}
else {
$i++;
}
}
print($i)
is a dead code - it will never get executed- Second, you don't need to check
else if(file_exists("../photo/$i.jpg"))
again. 00
is not valid integer, it's simplified to just 0, as 01 simplified to 1 (actually it's treated as octal digits, so08
and09
is invalid)
So, to have the real 00
, 01
, 02
you'll have to format your output with spritf
$q=0;
$file_suffix = sprintf("%02d", $q);
if(!file_exists("../photo/{$file_suffix}.jpg")){
print($i);
return $i;
}
else{
$q+=1;
}
精彩评论