Home > PHP > Generating Random Number in PHP

Generating Random Number in PHP

September 24th, 2009 Captain Leave a comment Go to comments

Generating random numbers is very important in programming. We have to use random numbers to show a random record (Image, Saying, Article etc.) on our pages. Also, we can use random numbers for everything that we can imagine. In this article, we will see easiness of generating random numbers with PHP.


Structure 1.0: This is basic statement(void function) and we don’t determine nothing like maximum or minimum limit.

1
<?rand();?>

Example 1.0:

1
<?echo(rand());?>

Probable Output of Example 1.0:

1
652696728

1.1) Generating a Random Number Between Two Numbers

Structure 1.1: If we want to generate a random number between two numbers (that we determined), we should define two parameters.

1
<?rand(int MinNum,int MaxNum);?>

Formula: MinNum <= result <= MaxNum

Example 1.1: In this using, a random number is generated between 1000 and 2000(inclusive)

1
<?echo(rand(1000,2000));?>

1.2)Getting a Random Element from a Collection

Example 1.2: Assume that we need to get a random item from an array.

1
2
3
4
<?
$my_array=array('ASP','PHP','JAVASCRIPT','AJAX','CSS','JQUERY','HTML');
echo($my_array[rand(0,6)]);
?>

Probable Output of Example 1.2:

1
PHP

Let’s improve our example…


Example 1.3: This time, we going to get multiple items from an array.

1
2
3
4
5
6
7
8
<?
$my_array=array('ASP','PHP','JAVASCRIPT','AJAX','CSS','JQUERY','HTML');
$repetition=rand(0,6);
for($i=0;$i<=$repetition;$i++){
echo('I am learning ' . $my_array[rand(0,6)]);
echo(' on Memiso.com<br />');
}
?>

Probable Output of Example 1.3:

1
2
3
4
5
6
I am learning JQUERY on Memiso.com
I am learning ASP on Memiso.com
I am learning AJAX on Memiso.com
I am learning PHP on Memiso.com
I am learning HTML on Memiso.com
I am learning PHP on Memiso.com

A Little Homework For You

As you see, it is possible getting duplicate elements. So, try to make an application that gets every single element from array only once.

Bookmark and Share
  1. No comments yet.
  1. No trackbacks yet.
eXTReMe Tracker