Your modified function:
function getRandomString( $length = 8 )
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$digits = '0123456789';
$string = '';
for( $i = 0; $i < 5; $i++ )
{
$string .= $digits[ mt_rand( 0, strlen( $digits ) - 1 ) ];
}
for( $i = 5; $i < $length; $i++ )
{
$string .= $characters[ mt_rand( 0, strlen( $characters ) - 1 ) ];
}
$array = str_split( $string );
shuffle( $array );
return implode( '', $array );
}
3v4l.org demo
Starting from your function, we divide $characters
in $characters
and $digits
, then we add to the empty string 5 random digits and remaining random characters.
At the end, we shuffle resulting string and return it.
Variant (not-repeating characters):
function getRandomString( $length = 8 )
{
$characters = str_split( 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' );
$digits = str_split( '0123456789' );
shuffle( $characters );
shuffle( $digits );
$retval = array_merge
(
array_slice( $digits, 0, 5 ),
array_slice( $characters, 0, $length-5 )
);
shuffle( $retval );
return implode( '', $retval );
}
We start directly with arrays: $characters
and $digits
, then we shuffle them, we extract 5 digit items and remaining character items, merging them in $retval
array.
At the end, we shuffle $retval
array and return it imploded as string.
Edit: precedent version 3 digits / 5 chars; actual version: 5 digits / 3 chars