# Generate Random Number

Hi All,
I'm using a news script called 'Cutenews' and within this script I can setup different news sections and each of these gets a number 1,2,3,4 etc. To display a news section on my web page I just drop in a piece of php with the appropriate news section number. This works great but I want to change it slightly. I want the news sections to appear randomly
\$section = 3
I want
\$section = a_random_number

I know how to generate a random number between 1-10, 1-20 etc but what I want to know is how to generate a random number from a list of given numbers e.g. if I have the numbers 1,3,4,6,8,9,10,12,15,18, how can I select one of these randomly?

Hope this is clear and many thanks in advance

Michael

LVL 10
###### Who is Participating?

Commented:
Use the rand function

example - random number between 1 and 10

\$var = rand(1,10);
echo \$var;

To get a random number out of a list you would be best advised to put the numbers in an array and select a random array index.

eg.

\$numbers = array(1,3,4,6,8,9,10,12,15,18);
\$random = \$numbers[rand(0,count(\$numbers)-1)];
echo \$random;
0

Commented:
Hi daleoran,

Have count of number of elements in the list. Generate a number in the range of 1 to count. Pick the counth element for display

Sunnycoder
0

Commented:
you could also just shuffle the array and return the first array item, eg:

\$numbers = array(1,3,4,6,8,9,10,12,15,18);
shuffle(\$numbers);
echo \$numbers[0];
0

Commented:
Slight correction

Have count of number of elements in the list. Generate a number in the range of 1 to count.
>Pick the counth element for display

I meant
Pick the randomly generated index number for display
0

Author Commented:
Many thanks for the prompt replies. Unfortunately I can't try these out until I get home this evening so please be patient

Michael

0

Commented: