Last active
January 10, 2024 01:06
-
-
Save ibnumardini/6d92002af78bba60d490ee603099c5bf to your computer and use it in GitHub Desktop.
Simple function to generate random string (number & capital number) in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// turn on strict type mode. | |
declare (strict_type = 1); | |
/** | |
* build your own random string. | |
*/ | |
function make_rand(int $key_length = 0, string $new_space = null): string | |
{ | |
if (!$key_length) { | |
return (string) null; | |
} | |
$key_space = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
if ($new_space) { | |
/** | |
* if $new_space available, concat to base $key_space & | |
* validate $new_space must be letters and numbers. | |
*/ | |
$key_space .= preg_replace('/[^A-Za-z0-9\-]/', rand(0, 9), $new_space); | |
} | |
$rand_string = ''; | |
for ($i = 0; $i < $key_length; $i++) { | |
$pos = rand(0, strlen($key_space) - 1); | |
$rand_string .= $key_space[$pos]; | |
} | |
// change the output to uppercase. | |
return (string) strtoupper($rand_string); | |
} | |
// make random string and a length is 10. | |
echo make_rand(10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fire