Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Last active June 25, 2024 18:52
Show Gist options
  • Save fmtarif/5781a161e48001d656564c7d226456ef to your computer and use it in GitHub Desktop.
Save fmtarif/5781a161e48001d656564c7d226456ef to your computer and use it in GitHub Desktop.
#php Generate a random code with pre-defined length and characters PHP
<?php
echo random_code(6); //E4QGR9
echo PHP_EOL;
echo random_digits(6); //610470
echo PHP_EOL;
echo random_chars(6); //XBRBDH
echo PHP_EOL;
echo random_code(6, 'ABC123'); //221B21
function random_digits($length) {
return random_code($length, join(range(0,9)));
}
function random_chars($length) {
return random_code($length, join(range('A', 'Z')));
}
//modified from https://stackoverflow.com/a/13169091
function random_code(
$length,
$chars = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'
) {
$result = '';
$char_length = strlen($chars);
for ($i = 0; $i < $length; $i++) {
$randomIndex = random_int(0, $char_length - 1);
$result .= $chars[$randomIndex];
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment