Laravel A non-numeric value encountered on functions

Moha

New Member
#1
What is the reason for the following error in code? The first time runs without problems, But the second time "A non-numeric value encountered" error occurs:
Mã:
 public function checkName(string $name, string $path, string $extension, int $num)
    {
        if (Storage::exists("$path/$name"))
        {
            $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $name);

            if ($num > 1)
                $withoutExt = str_replace('_'.$num-1, '_'.$num, $withoutExt);
            else
                $withoutExt = $withoutExt . '_'.$num;

            $newName = "$withoutExt.$extension";

            if (Storage::exists("$path/$newName")) {
                return $this->checkName($newName, $path, $extension, $num+1);
            }
            else
                return $newName;
        }

        return $name;
    }
Mã:
$fileNameSave = (new Attachment)->checkName($fileName, $filePath, $file->getClientOriginalExtension(), 1);
Mã:
exception: "ErrorException"
line: 84
message: "A non-numeric value encountered"
 

Admin

Administrator
Thành viên BQT
#2
This is because concatenation takes precedence here:
Mã:
'_'.$num-1
To fix the issue just wrap the subtraction in parentheses:
Mã:
str_replace('_'.($num-1), '_'.$num, $withoutExt);
 
Top