4

I am doing a little function to generate random usernames, as the following:

public static function nicknames($data) {
    if ($data['request'] == 'nickAvailable') {

        foreach ($data as $value)
            if (is_array($value))
                $nick = $value['nickname'];

        $random = rand(2, 2);
        $nickname = $nick . '_' . $random;

        $count = 3;
        $nicknames = array();
        for ($i = 1; $i <= $count; $i++) {
            $select = self::$db->select('users', 'nickname', array('nickname' => $nickname));

            if (count($select) == 0) {
                $nicknames[] = $nickname;
            } else {
                $count = $count + 1;
            }
        }

        $array = array("status" => 0,
            "errors" => $nicknames,
            "data" => array());

        model::json($array);
    }

}

The only problem I have is that $random is just executed one time and not on each loop. I need 3 different usernames to be in the array, and they must be different from each other. How can I edit my code to achieve this? Thanks for any suggestion

2 Answers 2

1

Place the random number generator and nickname building variable at the start of your loop. Also increase the range of numbers that rand is allowed to return, as it will always return 2 at the moment

$usernames = array();
do {

 // inside generate random number, 
 // build nickname, 
 // query to see if its taken, 
 // and if NOT taken, add to the usernames array

} while(count($usernames) < 3);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked. Is it correct to increase the value of $count in the case that the username already exists. I am doing it in my code as above, but I am not sure that the for loop will be actually incremented of 1 loop as I am expecting.
I've added a basic example of how i'd approach it, the way your incrementing the counter, will mean it only gets incremented when you find a duplicate username, which means your could end up generating millions of usernames, or getting NO usernames back at all if your first 3 generated names are already taken
1

As of now, you're not generating a random number.

$random = rand(2, 2);

This will always be 2.

Here's how I'd do it:

for ($i = 1; $i <= $count; $i++) 
    {

    $random = rand(1, 3);
    $nickname = $nick . '_' . $random;
        $select = self::$db->select('users', 'nickname', array('nickname' => $nickname));

        if (count($select) == 0) {
            $nicknames[] = $nickname;
        } else {
            $count = $count + 1;
        }
    }

Hope this helps!

Comments

Your Answer

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