FREE tutorial,solution,RSS Feeds on Operating Systems, Programming, Web Development, Applications, Databases, Networking, Hardware, Security, SEO Free Expertsforge Membership
Join us as Moderator
Submit Article to Expertsforge.com Submit Article My Expertsforge
 
RSS Feeds, Help Help RSS Feeds
bannertop
 

PHP Tutorial: Generating Random Numbers, Random Ads using PHP

jawahar
5/2/2005 1:16:52 AM, Views: 1990
I'd like to explore random numbers next in PHP. Let's do some code that will generate three random digits between 0 and 9. Random numbers are generated using the rand function.

<?
srand(time());
$random = (rand()%9);
print("random number between 0 and 9 is: $random");
?>


Example #12: Generating a random number between 0 and 9

Let's create a simple slot machine which will show random numbers between 0 to 3 (if you change the 3 to 9 it will be a lot harder to get all three numbers, of course). If you get all 3 numbers it will just print "Winner!" and the game will end. No scoring, just a simple exercise to show multiple random generation. Yeah, I know, it's not terribly useful, but I kind of enjoy a sidetrack once in awhile. Here's the code:

<?
function slotnumber()
{
   srand(time());
      for ($i=0; $i < 3; $i++)
      {
         $random = (rand()%3);
         $slot[] = $random;
      }
   print("<td width=\"33%\"><center>$slot[0]</td>");
   print("<td width=\"33%\"><center>$slot[1]</td>");
   print("<td width=\"33%\"><center>$slot[2]</td>");
      if($slot[0] == $slot[1] && $slot[0] == $slot[2])
      {
         print("</td></tr>Winner! -- Hit refresh on your browser to play again");
         exit;
      }
}
?>

<div align="center"><center>
<table border="1" width="50%">
<tr>

<?
slotnumber();
?>

</td></tr><tr>
<td width="100%" colspan="3" bgcolor="#008080">
<form method="POST" action="example13.php3">
<div align="center"><center><p><input type="submit" value="Spin!">
</p></center></div>
</form>
</td></tr>
</table></center></div>


Example #13: php simple slots - multiple number generation

Since I chose to have my numbers like an array, it would be very easy to add an array filled with various image.gifs (or .jpg) files and replace the rather plain numbers with graphic images. The code at the beginning of the function would look like this:

$images = array("image1.gif",
                        "image2.gif",
                        "image3.gif");


Now in place of your print line you would add the following:

print("<td width=\"33%\"><center><img src=$images[$slot[2]]></td>");


You might also want to simulate a six-side dice rolling. For this you would use the following code:

<?
srand(time());
$random = (rand()%6)+1;
print("Your 6-sided dice roll was $random");
?>


By changing the +1 to a higher positive number (+2, +3, +4, etc.) you could generate virtually limitless variation ranges of rand numbers (2-12, 4-20, 12-25, etc) between x and x. Can you write a script that will roll two six-sided dice? I'll leave this task for homework (no test, though) to you. I'll now use the rand function for more useful purposes here .

Random Ads Of The Day

I've always liked those random link of the day options. They are especially useful for advertising. That is going to be my use of it for now, since I can't really keep php-scripts.com advertising free forever. Well I could, but I'd rather do something to help pay for the bandwith. I
can make the advertising as non-intrusive as possible, however. What I'd like to do is provide a "random" link of the day to one of my Perl scripts. Why, you ask, this is a PHP script site, well ... because I don't have any PHP scripts to sell (at the time of writing this diary entry, that is). Perhaps at some point I will advertise third party goods and services here, but for now, simply putting up a small text link to one of my Perl scripts seems like a pretty good idea. You may not agree, but you can take action by giving today's diary entry a 1 for usefulness, lol. Here is one possible version of code I could use:

<?
$random_url = array("http://www.expertsforge.com/",
                              "http://www.expertsforge.com/rss-feeds/rss-feeds.asp",
                              "http://www.expertsforge.com/chat/",
                              "http://www.expertsforge.com/link-directory/");
$url_title = array("Expertsforge.com",
                            "FREE RSS Feeds",
                            "Expertsforge Chat",
                            "Link Directory");
$url_desc = array("- Free Archive of Tutorials, RSS Feeds","- FREE RSS Feeds, RSS to Javascript Converter","- Chat with Experts","- Put your website link here");

srand(time());
$random = (rand()%3);
print("<center><a href=\"$random_url[$random]\">$url_title[$random]
</a>");
print(" $url_desc[$random]</center>");
?>


Example #14: random text link ads

The HTML portion is pretty easy, it just involves another include tag where I want the random text link to appear, or I can call directly as above in the example.

<? include("random_text_ads.php3"); ?>


You might have looked at my code above and thought, hmmm, wouldn't it be better to have the links in a file, open the file, fill an array and pick a random link that way? If you want to be able to add links to it, yes, it would be easier, but not necessarily "better." When I coding I try to stay the path of least server resources. Since I knew the information I could just hardcode into an array without much work. However, if I want to be able to add links in the future, then using a file would surely be a lot more handy, then downloading the script, adding to the array, changing the random number and then re-FTPing my changes. It would be more efficient to use the count function to determine the size of the array and put that in place of the "3" in the rand function. After the $random_url variable is defined you would add this line:

$count = count($random_url_);


In place of the "3" in the $random variable code above you would put the $count variable like below:

$random = (rand()%$count);

Next Steps:
Add this Tutorial to:
Blink Blink del.icio.ous Del.icio.us Digg Digg
Fark Fark Furl Furl Google Google
Reddit Reddit Simpy Simpy Spurl Spurl
Technorati Technorati Windows Live Win Live Yahoo Yahoo
Rate Me!
Avg Visitor Rating: Average Visitor Rating is 3.5 out of 5
Number of Ratings : 2 Votes
Rate:
Send Private MessageSend Message
Signup / Login To View the Solution or Provide Comments
Post Comment/Solution
Comment:*
        (Link Rules) 
  Use : [bold] for <b>; [/bold] for </b>; [italic] for <i>; [/italic] for </i>; [code] & [/code] for code
 
Categories
Options
PHP RSS Feed
Most Popular Tutorial
Most Popular Solution
No Records!
Top Rated
Top Rankers
Overall
1. jawahar (500)
Yearly -2008
No Rankings!
Expertsforge Sponsors
bnrtop