PHP: using a switch to declare a string. Is this possible?

91 Views Asked by At

In the following code:

$num = Rand (1,2);
switch ($num)
{
case 1:
$var1 = "first value";
break;
case 2:
$var1 = "second value";
break;
}

My next part of coding needs the $var1 to be included inside an array of Jobs. Any idea how I would do this.

Thanks as always, Cameron.

2

There are 2 best solutions below

14
On

why not this? code example works for php5.5

$var1  = array("first val","second", "and so on ...")[rand(0,2)];


code example works for php<5.5

$vars = array("first val","second", "and so on ...");
$var1 = $vars[array_rand($vars)];
0
On

Both of this versions work for me:

$strings = array('string 1', 'string 2', 'string 3');
$rnd = array_rand($strings);


$string = $strings[$rnd];
echo $string;

switch ($rnd) {
    case 0:
        $string = $strings[0];
        break;

    case 1:
        $string = $strings[1];
        break;

    case 2:
        $string = $strings[2];
        break;
}
echo $string;