Quick PHP question: rand()

Hitman
Soldato
Joined
25 Feb 2004
Posts
2,837
Hi,

Trying to make a script to randomly choose between variables that I set in the script. Ideally I'm after something similar to this:

Code:
<?php

	$1 = '1';
	$2 = '2';
	$3 = '3';
	$4 = '4';
	$5 = '5';
	
	$pick = rand($1, $5);
	echo $pick;

?>

Is this possible? Obviously this doesn't work, but it's basically what I'd like to do.

Cheers
 
Ah I'm such a dummy, managed to solve it myself:

Code:
<?php

	$pick = rand(1, 5);
	$tmp = $pick;
	switch($tmp)
	{
		case 1:
			echo 'one';
			break;
		case 2:
			echo 'two';
			break;
		case 3:
			echo 'three';
			break;
		case 4:
			echo 'four';
			break;
		case 5:
			echo 'five';
			break;
	}

?>

Cheers for helping non-the-less, jdickerson :)
 
Or:

Code:
<?
	$a1 = 'this is one';
	$a2 = 'this is two';
	$a3 = 'this is three';
	$a4 = 'this is four';
	$a5 = 'this is five';
	
$pick = ${a.(round(rand(1, 5)))};

echo $pick;
?>

less lines :p
 
Much easier / nicer than mine :p

Perfect, thanks mate, really appreciated :)

jdickerson said:
Or:

Code:
<?
	$a1 = 'this is one';
	$a2 = 'this is two';
	$a3 = 'this is three';
	$a4 = 'this is four';
	$a5 = 'this is five';
	
$pick = ${a.(round(rand(1, 5)))};

echo $pick;
?>

less lines :p
 
jdickerson said:
Or:

Code:
<?
	$a1 = 'this is one';
	$a2 = 'this is two';
	$a3 = 'this is three';
	$a4 = 'this is four';
	$a5 = 'this is five';
	
$pick = ${a.(round(rand(1, 5)))};

echo $pick;
?>

less lines :p
But lots of duplication of 'this is ' ;)
 
marc2003 said:
strange logic there? if you have php then it's not as if any particular function is unavailable... :confused:
No, but given the fact the original format was used, I tried to stick to it.

Plus it is (marginally) easier to edit than an array.
 
Jaffa_Cake's method is my favourite, another way is

PHP:
<?php

$a = array(
	'a',
	'b',
	'c',
	'd',
	'e'
);

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

?>
 
Back
Top Bottom