Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP: Human-readable Random String
<?php
/**
* Generates human-readable string.
*
* @param string $length Desired length of random string.
*
* retuen string Random string.
*/
function readable_random_string($length = 6)
{
$string = '';
$vowels = array("a","e","i","o","u");
$consonants = array(
'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
);
$max = $length / 2;
for ($i = 1; $i <= $max; $i++)
{
$string .= $consonants[rand(0,19)];
$string .= $vowels[rand(0,4)];
}
return $string;
}
@laurent22

This comment has been minimized.

Copy link

@laurent22 laurent22 commented Mar 2, 2017

Works great, thanks a lot for sharing.

@laurent22

This comment has been minimized.

Copy link

@laurent22 laurent22 commented Mar 2, 2017

The only change I made is that I removed the srand call since a self-contained function shouldn't change global state. Also by default PHP's random seed is already initialised to a good enough value.

@serdarde

This comment has been minimized.

Copy link

@serdarde serdarde commented Oct 6, 2018

Nice function, thanks

@Seunope

This comment has been minimized.

Copy link

@Seunope Seunope commented Feb 23, 2019

Nice! Works like charm.

@nesrindagli

This comment has been minimized.

Copy link

@nesrindagli nesrindagli commented Mar 13, 2020

Works NICE, thanks!

@rjworks

This comment has been minimized.

Copy link

@rjworks rjworks commented Jul 7, 2020

thanks my brother

@indextwo

This comment has been minimized.

Copy link

@indextwo indextwo commented Aug 15, 2020

This is great, but I'd definitely remove the srand() function. Called in a loop 100,000 times, with a character length of 8, without that srand(), there are on average ~50 collisions (i.e. 50 non-unique words generated), which is 0.05%. Adding it back in increases the number of collisions a hundred-fold - anywhere from 4800 to 5600 collisions per loop (or ~5%).

Without srand() it's still not perfectly unique, but it is a lot better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.