Skip to content

Instantly share code, notes, and snippets.

@ibnumardini
Last active January 10, 2024 01:06
Show Gist options
  • Save ibnumardini/6d92002af78bba60d490ee603099c5bf to your computer and use it in GitHub Desktop.
Save ibnumardini/6d92002af78bba60d490ee603099c5bf to your computer and use it in GitHub Desktop.
Simple function to generate random string (number & capital number) in php
<?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);
@Rdx11
Copy link

Rdx11 commented Jan 10, 2024

Fire

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment