function genRandomString() { $length = 8; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ''; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } // Example $idhash = genRandomString(); while(alreadyExist($idhash)) // you must make this function yourself of course { $idhash = genRandomString(); }