'aaaaa...' throw new LogicException( 'random_str - Argument 3 - expected a string that contains at least 2 distinct characters' ); } // Now that we have good data, this is the meat of our function: $random_str = ''; for ($i = 0; $i < $length; ++$i) { if ($crypto_secure && function_exists('random_int')) { $r = random_int(0, $charset_max); } else { $r = mt_rand(0, $charset_max); } $random_str .= $charset[$r]; } return $random_str; } }