Random texts/images may be very cool, and sometimes, very useful. That"s why we have the function rand() in PHP, for generating random numbers, that will generate our random stuff.
Lesson 1: rand() basics
let"s start with a simple example:
this will print a number of 0 to 3. So, the syntax is: rand(min, max);
Lesson 2: random texts
we already know how to create random numbers, but how can we generate random texts?
simple, just use an array! See bellow:
<?php // All the texts $text = array( "1" => "rand is a nice function", "2" => "Hello world!", "3" => "visit php.net for php manual!", "4" => "using the function rand(), by Andreas Diegues" );
// Random number. You also can use count($texts) in rand argument 2 $rand = rand(1, 4);
// Print the text echo $text[$rand]; ?> |
Lesson 3: random images
generating random images is very simple. basically the same of random texts. See:
<?php // All the images $image = array( "1" => "<img src=http://www.devpapers.com/images/logo.gif>", "2" => "<img src=http://www.devpapers.com/images/earncash.gif>", "3" => "<img src=http://ads.inetdirectories.com/banman/ads/hs_120x90.gif>", "4" => "<img src=http://ads.inetdirectories.com/banman/ads/devlance_120x90.gif>" );
// Random number. You also can use count($image) in rand argument 2 $rand = rand(1, 4);
// Print the text echo $image[$rand]; ?> |
Lesson 4: random passwords!
using the function rand, you can also generate random passwords. it"s not so easy as the other lessons, but must be useful for everyone.
See the code, pay attention to the comments:
|
<?php // Our string will have 8 characters, but you can easy change for($i = 0; $i < 8; $i++) { // All the letters and numbers $type[1] = "A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|X|W|Y|Z"; $type[2] = "0|1|2|3|4|5|6|7|8|9";
// Change for letter or number $randType = rand(1, 2);
// Get an character alone $type = explode("|", $type[$randType]); // Get the total size of characters $max = count($type);
// Randonic character $randChar = rand(0, $max); $code .= $type[$randChar]; }
// Print the password echo "the password generated was: ".$code; ?> |
Finish! Very simple no? Numbers will be always helping us on PHP.
Good Luck!