I want to simplify the following:
<?php
//define $c
$c = 0;
//echo result
echo "a: " . $c . ", ";
//generic switch
switch ($c)
{
case 0:
echo "good ";
break;
case 1:
echo "better ";
break;
case 2:
echo "best ";
break;
}
//define $c
$c = 1;
//echo result
echo "b: " . $c . ", ";
//generic switch
switch ($c)
{
case 0:
echo "good ";
break;
case 1:
echo "better ";
break;
case 2:
echo "best ";
break;
}
//define $c
$c = 2;
//echo result
echo "c: " . $c . ", ";
//generic switch
switch ($c)
{
case 0:
echo "good ";
break;
case 1:
echo "better ";
break;
case 2:
echo "best ";
break;
}
?>
Which gives the following output:
a: 0, good b: 1, better c: 2, best
This has a large section (the switch) which is repeated several times, so I want to tidy the code and avoid replication.
I know I could use a while loop, but I don't want to (this code is simplified in itself - each part would be in different rows/columns of a table for the final purpose so a while loop wouldn't be suitable). In my vb days, I would have made a subroutine with the select case (switch) statement, so I tried the following:
<?php
function test()
{
switch ($c)
{
case 0:
echo "good ";
break;
case 1:
echo "better ";
break;
case 2:
echo "best ";
break;
}
}
$c = 0;
echo "a: " . $c . ", ";
test();
$c = 1;
echo "b: " . $c . ", ";
test();
$c = 2;
echo "c: " . $c . ", ";
test();
?>
However, this outputs:
a: 0, good b: 1, good c: 2, good
Why is it that the same switch statement won't work in a function? Is there any way around this?