I am using this piece of function to check if a file exists. If the file exists then I am changing its name:
function checkFileExist($fileName, $z, $ext, $folderWIthFileName){
$tmpNam = "";
if (file_exists($fileName . "_" . $z . "." . $ext)) {
$z = $z + 1;
checkFileExist($fileName, $z, $ext, $folderWIthFileName);
}
else {
$tmpNam = $fileName . "_" . $z;
echo "in else <br> " . $fileName . "_" . $z . "<br>";
}
return $tmpNam;
}
And calling this function like
$definename = checkFileExist($folderWIthFileName . "/" . $InvId, $z, $ext, $folderWIthFileName);
echo "new name is " . $definename;
But this gives me output like this:
in else
444_2015-10-27/444_3
new name is
You can see return is not working correctly. What am I doing wrong here?
You should use return checkFileExist($fileName, $z, $ext, $folderWIthFileName);
in the first block to return back a value from the recursively made calls. Use this clean version:
function checkFileExist($fileName, $z, $ext, $folderWIthFileName) {
if (file_exists($fileName . "_" . $z . "." . $ext)) {
return checkFileExist($fileName, $z+1, $ext, $folderWIthFileName);
}
return $fileName . "_" . $z;
}