# Random alphabet

``````\$randomNumber=rand(0,9);
``````

The code above produces a random number from 0 to 9.

How can I get \$randomAlphabet from a to z?

The code below seems not to work.

``````\$randomAlphabet=rand(a,z);
``````
1. put the letters in an array

2. generate random number between 0 - 25

3. get the array element value whose index is that from 2)

or depending on what you want to do, use [FPHP]shuffle[/FPHP]

If you’d read the manual, you would’ve know that.

rand — Generate a random integer

You could write a function that gets a random integer from 1 to 26, and then take the corresponding letter.

Edit: kalon’s 0-25 is better, because arrays start with key value 0.

If only there were a way to get from an integer to a character…

Wait. Don’t we have this thing called the ASCII table?

``````
chr(rand(97,122))

``````

I like taking the scenic route

and the ascii values for lower and upper case letters have a gap between them.

uppercase is 65 -90

Strings are small integers. Everything related to programming is based on numbers. Also, I’m amazed by the number of the topics started by dotJoon, all of these questions asked lately are easily found at google seeing they’ve been answered millions of times.

``````
<?php

\$letters = array_merge(range('a','z'),range('A','Z'));

echo \$letters[rand(0,51)];

?>

``````
``````
chr(rand() > 0.5 ? rand(65, 90) : rand(97,122))

``````

I’m really not a fan of creating arrays when solutions like the above are available …

a wise person once told me

There’s more than one way to skin a cat.

in this case I would use an array because if I forgot to document in comments what chars the integers represented, someone else, or even me, looking at the code in the future might have to go look them up.

creating the array makes it a lot easier for me to see what is going on in the code without running it or looking anything up.

In order to get random alphabet from a to c, I wrote the code below

``````<?php
\$alphabet=array("a","b","c");

echo \$alphabet[0];
echo \$alphabet[1];
echo \$alphabet[2];

\$random_number=rand(0,2);

echo \$random_number ;

\$random_alphabet=[COLOR="Red"]\$alphabet['\$random_number'[/COLOR]];

echo \$random_alphabet;
?>
``````

But the code above doesn’t work correctly. I guess the code in read has some problem.

How can I fix the problem?

You enclosed the \$random_number call in single quotes - So it’s looking for the value in the array that corresponds to \$randon_number I believe, just remember when you’re referencing the position of something in an array through an integer, don’t use quotes.

So

``````\$random_alphabet=\$alphabet[\$random_number];
``````

Works perfect.

How random does it need to be? rand() and mt_rand() are pseudo-random. That is, they fake it and are not qualified as cryptographically secure (i.e. someone can get the sequence if they guess the right seed). If you need truly random numbers, use random.org.