0

Let's say we have this variable:

$random = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 5);

It will generate a random string that is 5 letters long

E.g.

echo "Hi" . $random    ========  Hi qwueh

The problem with this is that only one random string is given to the variable $random. To generate a new string, you'll have to refresh the page.

Is there a way to retrieve a different, unique string every time the variable $random is called upon on the same page?

E.g.

echo "Hi" . $random    ========  Hi qwueh
echo "Hi" . $random    ========  Hi dasij
echo "Hi" . $random    ========  Hi furhf
echo "Hi" . $random    ========  Hi wuejf
1
  • 2
    I think what you are look for is: create a function Commented Aug 9, 2015 at 15:00

2 Answers 2

1

I think what you are look for is: to create a function

<?php
function getRandomName() {
    return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 5);
}

echo "Hi" . getRandomName(). "<br>\n";
echo "Hi" . getRandomName(). "<br>\n";
echo "Hi" . getRandomName(). "<br>\n";
echo "Hi" . getRandomName(). "<br>\n";
echo "Hi" . getRandomName(). "<br>\n";

Or, in object oriented programming style (OOP), which will make for sense for you in the long run:

<?php
class nameGenerator 
{
    protected $alphabet;
    protected $length;

    public function __construct($alphabet, $length) 
    {
        $this->alphabet = $alphabet;
        $this->length = $length;
    }

    public function getRandomName() 
    {
        return substr(str_shuffle($this->alphabet), 0, $this->length);
    }
}


$generator = new nameGenerator("abcdefghijklmnopqrstuvwxyz", 5);
echo "Hi" . $generator->getRandomName(). "<br>\n";
echo "Hi" . $generator->getRandomName(). "<br>\n";
echo "Hi" . $generator->getRandomName(). "<br>\n";
echo "Hi" . $generator->getRandomName(). "<br>\n";
echo "Hi" . $generator->getRandomName(). "<br>\n";
Sign up to request clarification or add additional context in comments.

Comments

1

Create a function and then you can call it as much as you want:

function randNum($s, $e) {
    return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), $s, $e);
}

echo "Hi " . randNum(0,5) . "\n";
echo "Hi " . randNum(0,5) . "\n";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.