I found this example at the php.net/manual,but could not get the whole concept in the example. It seems the example is missing some details.
Would be grateful if someone can simplify it for me. Here's the example:
I've found that the most useful thing to use do-while loops for is multiple checks of file existence. The guaranteed iteration means that it will check through at least once, which I had trouble with using a simple "while" loop because it never incremented at the end.
My code was:
$filename = explode(".", $_FILES['file']['name']); // File being uploaded
$i=0; // Number of times processed (number to add at the end of the filename)
do {
/* Since most files being uploaded don't end with a number,
we have to make sure that there is a number at the end
of the filename before we start simply incrementing. I
admit there is probably an easier way to do this, but this
was a quick slap-together job for a friend, and I find it
works just fine. So, the first part "if($i > 0) ..." says that
if the loop has already been run at least once, then there
is now a number at the end of the filename and we can
simply increment that. Otherwise, we have to place a
number at the end of the filename, which is where $i
comes in even handier */
if($i > 0) $filename[0]++;
else $filename[0] = $filename[0].$i;
$i++;
} while(file_exists("uploaded/".$filename[0].".".$filename[1]));
How can if($i > 0)
detect that a file ends with a number ? Does the loop refer to a preg_match ?