Everything In Between

The brutally honest, first-person account of Meitar Moscovitz’s life.

Generating Random Letters in PHP

with 2 comments

Generating random numbers in PHP isn’t much a problem thanks to functions like rand() or mt_rand() and so utilizing them is a no brainer, even for programming newbies. Generating random letters, however, is sometimes a little less intuitive.

The tricky thing about it is that computers are basically glorified switches. All they do is answer the question “Is this a 0 or a 1?” for any given datum. So while this makes them pretty good at handling numeric data, doing anything interesting with something else, such as natural languages, requires a bit of creativity.

The concept of what a “letter” is or is not needs to be explicitly defined in some manner that computers (glorified switches) can understand. This is accomplished by mapping a numeric value to a specific character. This map is then known as a character encoding.

I’m not going to get into the whole thing here. For the curious, a pertinent Google search turned up this tutorial which is a good place to start. Additionally this informative article by Joel Spolsky is an entertaining and educational read.

However, back to PHP and generating random letters, we can sidestep the whole issue of encodings as long as the pool of possible letters we wish to generate is somewhat limited. Thanks to a feature of PHP that allows us to pick out a character in a string using array syntax, we can get a random letter with a random number and a string containing the possibilities we want.

function randLetter()
{
    $int = rand(0,51);
    $a_z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $rand_letter = $a_z[$int];
    return $rand_letter;
}

While this method may carry a little more overhead than a purely numeric approach, it’s certainly easier to digest.

Written by Meitar

December 19th, 2004 at 10:02 pm

Posted in PHP, Programming

2 Responses to 'Generating Random Letters in PHP'

Subscribe to comments with RSS or TrackBack to 'Generating Random Letters in PHP'.

  1. You could always use:
    function randLetter()
    {
    return chr(97 + mt_rand(0, 25));
    }

    This gives you a random lower case letter… if you need both i guess a quick conditional statment could create a lower- or uppercase letter if in the 0-25 or 26-51 range… hmmm…

    Have a look at Ascii Table for details of ordinal numbers for characters in ASCII.

    Samuel Cochran

    2 Jan 05 at 4:45 AM

  2. Naturally, this would be “the programmer’s way” of doing it, but this requires some knowledge of what encodings are and how to represent them mathematically. The whole point of using PHP’s array syntax is to avoid this necessity. That said, its obviously better to do things your way than mine when optimizations and memory considerations are important to take into account.

    Meitar

    2 Jan 05 at 6:31 PM

Leave a Reply