Home > Net >  How to pass random length of a function in PHP
How to pass random length of a function in PHP

Time:12-13

I have a bit of code, which generates a random string, however I also want the length of the string to be random.

I have this code right now:

$len = rand(0, 50);

function generateRandomString($length = $len) {
    $characters = '0 1 2 3 4 5 6 7 8 9 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i  ) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

However, this gives me an error saying "Fatal error: Constant expression contains invalid operations". Is there any way of passing a random length value to the function?

Thank you

CodePudding user response:

You can try this. The user can enter a random length and if not provided the function auto generates a random length of its own.

function generateRandomString($length = null)
{
    $characters = '0 1 2 3 4 5 6 7 8 9 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';

    $length = $length ? $length : rand(0, 50);

    for ($i = 0; $i < $length; $i  ) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

    return $randomString;
}

var_dump(generateRandomString()); // works
var_dump(generateRandomString(4)); // also works
  •  Tags:  
  • php
  • Related