PHP Random String Function

I was testing a string manipulation function today (which I will post some other time) and I wanted to create a random string of characters that I could feed into it, so I came up with the function below. I thought it was a neat use of the rand() and chr() PHP functions, so here it is.

function random_string($length = 50) {
    $string = '';

    for ($i = 0; $i < $length; ++$i) {
        
        $type = rand(1, 5);

        switch ($type) {
            case 1:
                // lowercase letters
                $ascii_start = 65;
                $ascii_end = 90;                
                break;
            case 2:
                // uppercase leters
                $ascii_start = 97;
                $ascii_end = 122;
                break;        
            case 3:
                // Space
                $ascii_start = 32;
                $ascii_end = 32;                
                break;   
            case 4:
                // numbers
                $ascii_start = 48;
                $ascii_end = 57;                
                break;
            case 5:
                // Punctuation
                $ascii_start = 33;
                $ascii_end = 47;
                break;
        }
        
        $string .= chr(rand($ascii_start, $ascii_end));
    }
    return $string;
}

It works by picking a type of character to use (eg, uppercase letter, number etc) and then selecting one at random using the chr() function. The chr() function takes a number as a parameter and will return the ascii character corresponding to that number. For example, given the number 65 the chr() function will return the string 'A'. It will loop over this selection process to build a string.

Here are some examples of the sort of output this function produces.

ye 82 C!4p $$r" lg 3 Ed-W KGrX1% 21V V"mENV YzA B 
 1% .AjU  C/7 E7 %3uplK g40-'$ i,j% E+JYh  Ox AU7I
 %q. v$ ,#H5t *d %9Xv59* *oZ3Hj-'G1- 2*7 a+I8Jy& 0
$)V, 7&g6o$3 u27 g"  p6 O* eU"LG Th 9J,&3*  zH)+*e
&5  u$/l)L0 MZ2'H 1MrymE X h3 66 4AW )WT1f  0 zQtF
- CAc2U'QU*1E5 -MfQ $ HMGJ0xg%,J0  q27r s 4oFz!74"
h Dx.h"Cq1ANF0S- S8w!z%hS  x%D8M'O(6a) 3r8H#$#./&i
a .!J (As3a!v&DXK0PIf1$B0JR Pp,KrM (/uUz22gm S% ,-
 *5j$,%0+ VSsz,a0oA7)' s9J$5/ R"iK3cvz GDQn3DC'"lc
6 xK,r2 R/1Y"y46S& s39#US   p*h1+2R8,0yr6 -HYG 'N"

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
1 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.