Random String Generator PHP Function Programming Tutorial

Published :
Author :
Adam Khoury
Learn to program a PHP random string generator that can be as long as you specify. We demonstrate how to then make your script modular in order for it to be reusable, external and dynamic. Splitting (str_split) any string gives you an array from that string, then you can pluck out elements of that array (array_rand) within a for loop in order to return a randomly generated string of characters of any length. <?php function randStrGen($len){ $result = ""; $chars = "abcdefghijklmnopqrstuvwxyz$_?!-0123456789"; $charArray = str_split($chars); for($i = 0; $i < $len; $i++){ $randItem = array_rand($charArray); $result .= "".$charArray[$randItem]; } return $result; } // Usage example $randstr = randStrGen(200); echo $randstr; ?>