Reputation: 57
I came across a problem when trying to implement a switch statement. Basically, I am trying to have multiple variables go through the same switch statement in order to prevent myself from repeating unnecessary code.
I have the variables $mon1
, $tue1
, $wed1
, $thu1
, $fri1
and I'd like to get all five of those variables individually through the switch statement below. I could simply add a new switch statement for each individual variable but it just seems like there would be a better way to handle this.
EDIT: I added a for each loop and this works rather well. I still have an issue, that being the assignment of variables. If - for example - $mon1 goes through case "3" then the value of $mon1 should be 13 at the end of the switch statement. Currently it does not assign that value. Any pointers?
$stress = array($mon1,$tue1,$wed1,$thu1,$fri1);
foreach($stress as $value){
switch ($value) {
case "1":
echo "This is 10";
$value = 10;
break;
case "2":
echo "This is 12";
$value = 12;
break;
case "3":
echo "This is 15";
$value = 15;
break;
case "4":
echo "This is 17";
$value = 17;
break;
case "5":
echo "This is 19";
$value = 19;
break;
}
}
Upvotes: 2
Views: 423
Reputation: 28499
You can use a function for this purpose:
function DecideStressByDay($value)
{
switch ($value) {
case "1":
$value = 10;
break;
case "2":
$value = 12;
break;
case "3":
$value = 15;
break;
case "4":
$value = 17;
break;
case "5":
$value = 19;
break;
}
return $value;
}
$mon1 = DecideStressByDay($mon1);
$tue1 = DecideStressByDay($tue1);
...
Upvotes: 1
Reputation: 3899
How about code like this:
$stresses = array(
$mon1 => array(10, 12, 13, 17, 19),
$tue1 => array(10, 12, 15, 17, 19),
$wed1 => array(10, 12, 15, 17, 19),
$thu1 => array(10, 12, 15, 17, 19),
$fri1 => array(10, 12, 15, 17, 19)
);
/* change constants as per your situation */
foreach($stresses as $day => $stress ){
$switch ($day) {
case "1":
$value = $stress[0];
break;
case "2":
$value = $stress[1];
break;
case "3":
$value = $stress[2];
break;
case "4":
$value = $stress[3];
break;
case "5":
$value = $stress[4];
break;
}
/* do something with $value here or it'll get overwritten with every loop*/
}
Upvotes: 0