Ive got the following snippet of code, which works and does what I need it to do. The only problem is I think its a little ‘verbose’ and can do with some optimising. Can someone help me reduce the repetitiveness if at all possible. Most of the code is very similar…
Many thanks
<?php
// condition = Less Than; More Than; Between
// noofweeks = this is the number of weeks chosen by the user
function fmsSupplements($condition, $conditionWeeks, $noofweeks, $weekno, $weekStartno, $weekEndno, $basicprice, $supplementAmnt, $supplementType) {
if ($condition== "Between") {
// I need to get the start and end values as the data in this parameter should look like 1-17
$betweenArray = explode('-',$conditionWeeks);
$startWeek = $betweenArray[0];
$endWeek = $betweenArray[1];
}
if(($condition == "Less Than") && ($noofweeks < $conditionWeeks) && ($supplementType == 'Subtract') && ($weekno >= $weekStartno && $weekno <= $weekEndno) ) { return $basicprice - $supplementAmnt; }
elseif(($condition == "Less Than") && ($noofweeks < $conditionWeeks) && ($supplementType == 'Add') && ($weekno >= $weekStartno && $weekno <= $weekEndno) ) { return $basicprice + $supplementAmnt; }
elseif(($condition == "More Than") && ($noofweeks > $conditionWeeks) && ($supplementType == 'Subtract') && ($weekno >= $weekStartno && $weekno <= $weekEndno) ) { return $basicprice - $supplementAmnt; }
elseif(($condition == "More Than") && ($noofweeks > $conditionWeeks) && ($supplementType == 'Add') && ($weekno >= $weekStartno && $weekno <= $weekEndno) ) { return $basicprice + $supplementAmnt; }
elseif(($condition == "Between") && ($noofweeks >= $startWeek && $noofweeks <= $endWeek) && ($supplementType == 'Add') && ($weekno >= $weekStartno && $weekno <= $weekEndno) ) { return $basicprice + $supplementAmnt; }
elseif(($condition == "Between") && ($noofweeks >= $startWeek && $noofweeks <= $endWeek) && ($supplementType == 'Substract') && ($weekno >= $weekStartno && $weekno <= $weekEndno) ) { return $basicprice - $supplementAmnt; }
//if no conditions match, just return the unaltered basic price back
else { return $basicprice ;}
;} ?>
That one list of ifs can be written as a nested if.
The most important changes:
($weekno >= $weekStartno && $weekno <= $weekEndno)is part of allconditions, so it is in the outer if.
that match with the given condition string are put in 1 if using or
(
||).Addresults in anaddition.
Subtractin a subtraction.All comes down to repeating the conditions as less as possible, although you should keep in mind that the structure should still be clear. In some cases, it may be easier your way.
In a different setup, I put the intermediate results in separate variables, which I think
makes it even more readable. I added a little more comments here, explaining the decisions: