php 5 to php 7.4

metroedu

New member
Below is a function I have used for over 10 years in PHP 5. Now going to PHP 7.4 I get an error because of "curly braces". Can anybody tell me how/what I should change?
function random_string($Ncharacters) {
static $CharList = "QWERTYUPKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm";
$String = "";
$Max = strlen($CharList)-1;
for ($i=0; $i<$Ncharacters; $i++) {
$String .= $CharList rand(0, $Max);
}
return $String;
}
Thanks for your help!
Juergen
 
The issue in your code is that you are missing a concatenation operator (.) between $CharList and rand(0, $Max) when appending characters to the $String variable. Additionally, PHP 7.4 introduced stricter error reporting, which may be why you are now encountering an error. To fix the code and make it compatible with PHP 7.4, you should update the line inside the for loop as follows:
$String .= $CharList . $CharList[rand(0, $Max)];

Here's the updated code:
function random_string($Ncharacters) {
static $CharList = "QWERTYUPKJHGFDSAZXCVBNMqwertyupkjhgfdsazxcvbnm";
$String = "";
$Max = strlen($CharList) - 1;
for ($i = 0; $i < $Ncharacters; $i++) {
$String .= $CharList . $CharList[rand(0, $Max)];
}
return $String;
}

With this change, the code should work correctly in PHP 7.4 and concatenate random characters to the $String variable.
 
To fix the issue with curly braces in your PHP function when transitioning from PHP 5 to PHP 7.4, make the following modification:
Change the line $String .= $CharList rand(0, $Max); to $String .= $CharList[rand(0, $Max)];.
This adjustment ensures that the random character is correctly appended to the $String variable. After applying this change, the function should work without any errors in PHP 7.4.
 
Back
Top