Can anyone help me with the following function, why return
inside switch case is working (return correct converted price/quantity):
function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
switch ($unit_id) {
case 8: // A Bushel
$outQ = $quantity / $lbs_in_a_bu;
$outP = $price * $lbs_in_a_bu;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 10: // Pounds
$outQ = $quantity;
$outP = $price;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 11: // CWT
$outQ = $quantity / LBS_IN_CWT;
$outP = $price * LBS_IN_CWT;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 12: // Metric Tonne
$outQ = $quantity / LBS_IN_TON;
$outP = $price * LBS_IN_TON;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
case 136: // W Bushel
$outQ = $quantity / $lbs_in_w_bu;
$outP = $price * $lbs_in_w_bu;
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
}
}
But this one is not? (return only case 136
converted price/quantity) ( return
after switch is not working) How can I improve from the above one, I want to use less code to do the above function, thanks!
function calcPriceAndQuantityFromLBS($price, $quantity, $unit_id, $lbs_in_a_bu, $lbs_in_w_bu) {
switch ($unit_id) {
case 8: // A Bushel
$outQ = $quantity / $lbs_in_a_bu;
$outP = $price * $lbs_in_a_bu;
case 10: // Pounds
$outQ = $quantity;
$outP = $price;
case 11: // CWT
$outQ = $quantity / LBS_IN_CWT;
$outP = $price * LBS_IN_CWT;
case 12: // Metric Tonne
$outQ = $quantity / LBS_IN_TON;
$outP = $price * LBS_IN_TON;
case 136: // W Bushel
$outQ = $quantity / $lbs_in_w_bu;
$outP = $price * $lbs_in_w_bu;
}
return ['quantity' => number_format($outQ, 3, '.', ''), 'price' => number_format($outP, 8, '.', '')];
}
Add the break;
statement at the end of each case
. Otherwise the code of the next case
s of the switch
statement will be executed too. Your return
statement uses variables that are defined in the switch
statement. If somehow $unit_id
is not in the list of case
s, the return
will fail in error. To prevent the return
from failing, you could add this at the bottom of the case list:
default: // $unit_id not found
return ['quantity' => '0.000', 'price' => '0.000']; // whatever you like
Or you could throw an Exception.
Return退出该函数,因此在您的情况下充当中断,这就是为什么它在第一种情况下起作用的原因。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.