Forum Moderators: coopster

Message Too Old, No Replies

Is there a more efficient way?

         

chocorol

5:20 pm on Aug 13, 2007 (gmt 0)

10+ Year Member



I'm using the following code to print random stuff in my site but I was wondering if there's a more efficient way to do it, using less code. I'm pretty sure there's a better way to do it.

$a = 'example1';
$b = 'example2';
$c = 'example3';
$d = 'example4';
$e = 'example5';
$f = 'example6';

$num = rand(1,6);

if ($num == 1) {echo $a;}
if ($num == 2) {echo $b;}
if ($num == 3) {echo $c;}
if ($num == 4) {echo $d;}
if ($num == 5) {echo $e;}
if ($num == 6) {echo $f;}

Duskrider

5:25 pm on Aug 13, 2007 (gmt 0)

10+ Year Member



How about this:

$examplearray = array('example1','example2','example3','example4','example5','example6');

$num = rand(0,count($examplearray)-1);

echo $examplearray[$num];

jatar_k

5:47 pm on Aug 13, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



nice, though you may be able to reduce one more line

$examplearray = array('example1','example2','example3','example4','example5','example6');

echo $examplearray[rand(0,count($examplearray)-1)];

chocorol

6:20 pm on Aug 13, 2007 (gmt 0)

10+ Year Member



wow, nice solutions guys. thanks a lot

Habtom

5:04 am on Aug 14, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Slightly simpler:

$input = array("Example1", "Example2", "Example3", "Example4", "Example5");
echo $input[array_rand($input)];

[edited by: Habtom at 5:05 am (utc) on Aug. 14, 2007]

coopster

2:04 am on Aug 15, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



shuffle [webmasterworld.com] works too.