Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

create random string

Posted on 2011-09-23
1
Medium Priority
?
337 Views
Last Modified: 2012-05-12
Hello, I have a function which is supposed to create a random 8 character string, it works most of the time, but sometimes it creates a 7 character string.. very weird, please help...

function genRandomString() {
    $length = 8;
    $characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $string = "";    
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}
0
Comment
Question by:jblayney
1 Comment
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 2000 total points
ID: 36588071
Try to fix your function this way:


function genRandomString() {
    $length = 8;
    $characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $string = "";    
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters)-1)];
    }
    return $string;
}

Cheers
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question