function Random::name

Same name in other branches
  1. 9 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::name()
  2. 10 core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::name()
  3. 11.x core/lib/Drupal/Component/Utility/Random.php \Drupal\Component\Utility\Random::name()

Generates a random string containing letters and numbers.

The string will always start with a letter. The letters may be upper or lower case. This method is better for restricted inputs that do not accept certain characters. For example, when testing input fields that require machine readable values (i.e. without spaces and non-standard characters) this method is best.

Parameters

int $length: Length of random string to generate.

bool $unique: (optional) If TRUE ensures that the random string returned is unique. Defaults to FALSE.

Return value

string Randomly generated string.

See also

\Drupal\Component\Utility\Random::string()

1 call to Random::name()
Random::object in core/lib/Drupal/Component/Utility/Random.php
Generates a random PHP object.

File

core/lib/Drupal/Component/Utility/Random.php, line 110

Class

Random
Defines a utility class for creating random data.

Namespace

Drupal\Component\Utility

Code

public function name($length = 8, $unique = FALSE) {
    $values = array_merge(range(65, 90), range(97, 122), range(48, 57));
    $max = count($values) - 1;
    $counter = 0;
    do {
        if ($counter == static::MAXIMUM_TRIES) {
            throw new \RuntimeException('Unable to generate a unique random name');
        }
        $str = chr(mt_rand(97, 122));
        for ($i = 1; $i < $length; $i++) {
            $str .= chr($values[mt_rand(0, $max)]);
        }
        $counter++;
    } while ($unique && isset($this->names[$str]));
    if ($unique) {
        $this->names[$str] = TRUE;
    }
    return $str;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.