...

View Full Version : Random Background Color



Len Whistler
06-11-2004, 02:54 AM
Hello...

I am working on a php script that will randomly set the background color from a set of colors I have chosen. Below is what I have so far, but it doesn't work properly.

I want the script to pick one of the 3 colors, but it picks a range of numbers between 000000 and 444444. The second number is ignored. Also I would like the script to work with hex numbers (ff0000). I don't think the RAND function works with hex numbers.




<?php

$background = array ('000000', '999999', '444444');
$number = rand($background[0], $background[2] );

echo "<body bgcolor=\"#";
echo "$number\">";
?>


Thanks for any help.

Sincerely

Leonard Whistler
www.stubby.ca

firepages
06-11-2004, 05:11 AM
rand returns a number between the 2 values supplied , so if you say rand(10,1000) you get an integer between 10 & 1000.... you are almost there , but you actually want a number between (with 3 array elements) 0 & 2 !

try this



<?
$background = array ('000000', '999999', '444444');
$number = rand( 0 , (count($background)-1) );
echo '#'.$background[$number];
?>


I used 0,(count()-1) so you can add as many colors to the array as you want and it will still work

Len Whistler
06-11-2004, 05:20 AM
Thanks firepages....

...It's late now but in the morning I will be checking out your code.

Leonard Whistler
www.stubby.ca

trib4lmaniac
06-24-2004, 09:57 PM
Create your own function to return a random hex code:

function rand_hex()
{
for($i=0;$i<10;$i++)
$chars[]=$i; // first 10 digits
$chars[]='a'; $chars[]='b'; $chars[]='c'; // chars a-c
$chars[]='d'; $chars[]='e'; $chars[]='f'; // chars d-f
$result="#";
for($i=0;$i<6;$i++)
$result.=$chars[rand(0, 15)];
return $result;
}
Then
<body bgcolor="<?=rand_hex()?>">

trib4lmaniac
06-25-2004, 09:40 PM
Oops, I didn't read your post properly :o Never mind I can stil contribute :D



<?
$background = array ('000000', '999999', '444444');
$number = rand( 0 , (count($background)-1) );
echo '#'.$background[$number];
?>

could become....

$bgcolors=array('#000000', '#999999', '#444444');
echo $bgcolors[array_rand($bgcolors)];



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum