1

Random Functions

Random Functions via @largestartist Posted by Jose Cuadra on July 21, 2008 Tags: | | | | Filed Under: References

Random text or images is an easy feature to deploy that can develop interest on a project. Any application can benefit from not presenting the same information over and over during every visit. I have listed examples in JavaScript, ActionScript, PHP, and Coldfusion.

JavaScript

//Array Declaration
var myArray = new Array();
myArray[0] = "Vanilla";
myArray[1] = "Chocolate";
myArray[2] = "Butter Pecan";
myArray[3] = "Strawberry";
myArray[4] = "Neapolitan";
myArray[5] = "Chocolate Chip";
myArray[6] = "French Vanilla";
myArray[7] = "Cookies and Cream";
myArray[8] = "Vanilla Fudge Ripple";
myArray[9] = "Praline Pecan";
//Random Whole Number up to Arrays Length
var randNo = Math.round((myArray.length-1)*Math.random());
//Output
document.write(myArray[randNo]);

ActionScript

//Array Declaration
var myArray:Array = new Array();
myArray[0] = "Vanilla";
myArray[1] = "Chocolate";
myArray[2] = "Butter Pecan";
myArray[3] = "Strawberry";
myArray[4] = "Neapolitan";
myArray[5] = "Chocolate Chip";
myArray[6] = "French Vanilla";
myArray[7] = "Cookies and Cream";
myArray[8] = "Vanilla Fudge Ripple";
myArray[9] = "Praline Pecan";
//Random Whole Number up to Arrays Length
var randNo = Math.round((myArray.length-1)*Math.random());
//Output
trace(myArray[randNo]);

PHP

$myArray[0] = "Vanilla";
$myArray[1] = "Chocolate";
$myArray[2] = "Butter Pecan";
$myArray[3] = "Strawberry";
$myArray[4] = "Neapolitan";
$myArray[5] = "Chocolate Chip";
$myArray[6] = "French Vanilla";
$myArray[7] = "Cookies and Cream";
$myArray[8] = "Vanilla Fudge Ripple";
$myArray[9] = "Praline Pecan";
//Random Whole Number up to Arrays Length
$randNo = rand(0,count($myArray)-1);
//Output
print $myArray[$randNo];

Coldfusion

<!--- Array Declaration --->
<cfset myArray=ArrayNew(1)>
<cfset myArray[1]="Vanilla">
<cfset myArray[2]="Chocolate">
<cfset myArray[3]="Butter Pecan">
<cfset myArray[4]="Strawberry">
<cfset myArray[5]="Neapolitan">
<cfset myArray[6]="Chocolate Chip">
<cfset myArray[7]="French Vanilla">
<cfset myArray[8]="Cookies and Cream">
<cfset myArray[9]="Vanilla Fudge Ripple">
<cfset myArray[10]="Praline Pecan">
<!--- Random Whole Number up to Arrays Length --->
<cfset randNo = RandRange(1, ArrayLen(myArray))>
<!--- Output --->
<cfoutput>#myArray[randNo]#</cfoutput>

Want More? Try These.

Related Articles
Target Blank for XHTML
Flash Slideshow in Actionscript 3
Random Articles
Color Picker
Multiple On Load Events
5 Pointz by Passetti
Table Behavior without Tables
Posemaniacs Anatomy
Random Functions
25 Free Font Sites
Twitter Highlights of the Week
Reiq’s Corel Painter Tutorial
From Work Path to Shape Layer

One Response to “Random Functions”

  1. Sexy Buzzoms says:

    Thanks for the tips! Even though I’m just starting JS I totally get it, very clear and easy to follow.

Leave a Reply