Jump to content


Photo
- - - - -

Randomizing array.


  • Please log in to reply
1 reply to this topic

#1 Redikate

Redikate

    Young Padawan

  • Members
  • Pip
  • 3 posts

Posted 12 July 2007 - 07:24 AM

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 ;)

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

Let begin with the easiest solution:

<?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.

<?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. ;)
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?

Edited by Redikate, 12 July 2007 - 07:30 AM.


#2 rc69

rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 13 July 2007 - 03:04 PM

Note there are a couple of built-in functions for this.
shuffle()
array_rand()

Edited by rc69, 13 July 2007 - 03:07 PM.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users