I have a while loop issue in PHP that seems like it could have been solved using the ampersand sign to make it a reference if it were elsewhere. Below is an example. I’m trying to append _n to the filename (in the basename). If there’s _1 then I want it to be _2, if there’s _2 I want it to be _3 and so on. For some reason I can’t update the $filename variable in the condition so I think it’s not getting changed in the loop.
$dir = 'images';
$filename = '123.jpg';
$i = 0;
while (file_exists($dir.'/'.$filename)) {
$filename = preg_replace('/^(\d*?)(\.jpg)$/',"$1_".(++$i)."$2",$filename);
}
echo $filename;
What am I doing wrong?
It looks like your regex is a little off, and you are not capturing the
_nif it already exists.