PHP generates random usernames

I perform a small function to generate random usernames, for example:

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 encountered is that $random only executes once, and not in every loop. I need the array to have 3 different usernames and they must be different from each other. How can I change my code to achieve this? Thanks for any suggestion.

+4
source share
2 answers

Place the random number generator and the alias string variable at the beginning of your loop. Also increase the range of numbers returned by rand, since 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); 
+1
source

You are not currently generating a random number.

 $random = rand(2, 2); 

It will always be 2 .

Here's how I would 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!

+1
source

Source: https://habr.com/ru/post/1492716/


All Articles