Help - Search - Members - Calendar
Full Version: Randomizing array.
Pixel2Life Forum > Member Tutorials and Requests > Forum Tutorial Archives > PHP Tutorials
Redikate
So, this is a little tutorial about randomizing something and it includes only PHP code so i expect that you know how to use it yourself smile.gif

------------------------------------------------

Let begin with the easiest solution:

CODE
<?php
$random_thing = array('Random1','Random2','Random3','Random4'); // this is an array where you put things you need to randomize. Seperate things with ,(comma).
$lets_randomize = rand(0,count($random_thing)-1); // this counts how many things you have in array and randomizes a number.
echo $random_thing[$lets_randomize]; // this echo's a randomized array value.
?>


Above code have one problem. It may randomize same number 2 times. That means it echos Random1 in the first place and if you refresh page it may echo Random1 again.
We are going to avoid that with SESSIONS.

CODE
<?php
session_start(); // let's start sessions
$random_thing = array('Random1','Random2','Random3','Random4'); // this is an array where you put things you need to randomize. Seperate things with ,(comma).
$lets_randomize = rand(0,count($random_thing)-1); // this counts how many things you have in array and randomizes a number.
while($lets_randomize == $_SESSION["last"]) // aslong as last generated number is same as the new one this code keeps making a new number
{
$lets_randomize = rand(0,count($random_asi)-1);
}
echo $random_thing[$lets_randomize]; // this echo's a randomized array value.
$_SESSION["last"] = $lets_randomize; // writes the last generated number to SESSIONS
?>


------------------------------------------------

So that's all for now.
Any comments/critism/fixes etc may be posted here.
I know this is not professional coding but i hope it will help some people out. rolleyes.gif
There may be mistakes in english as that is not my mother tongue.

EDIT: To add this tutorial to site... I will re-write it in the P2L tutorial-write or i can link to forum post?
rc69
Note there are a couple of built-in functions for this.
shuffle()
array_rand()
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.