Write a function to compute the discount and tax when you pay for a shopping items in a shop. Discount is 20% if the total order > $200, else the discount is 0. Tax is 7% of the total order after discount.
JavaScript
x
<?php
function computeDiscountAndTax($discount, $tax){
$totalOrder = 100;
if ($totalOrder > 200){
$discount = ($discount/100) * $totalOrder;
$tax = ($tax/100) * ($totalOrder - $discount);
return array($discount, $tax);
} else {
$tax = ($tax/100) * $totalOrder;
}
}
$result_array = computeDiscountAndTax(0, 7);
echo "Discount: " . $result_array[0] . "<br>";
echo "Tax: " . $result_array[1] . "<br>";
?>
Advertisement
Answer
Your problem is you’re not returning anything after else
. You set tax
to equal something, but you don’t return it.
The following will get you the output that you’re expecting.
JavaScript
<?php
function computeDiscountAndTax($discount, $tax){
$totalOrder = 100;
if ($totalOrder > 200){
$discount = ($discount/100) * $totalOrder;
$tax = ($tax/100) * ($totalOrder - $discount);
return array($discount, $tax);
} else {
return array(0, ($tax/100) * $totalOrder);
}
}
$result_array = computeDiscountAndTax(10, 7);
echo "Discount: " . $result_array[0] . "<br />";
echo "Tax: " . $result_array[1] . "<br />";
However, it should be noted, there is a lot odd about what you’re doing. Why is the total hard-coded inside the function? Why are you returning the values as non-associative array? This has the potential of getting really confusing really fast.
I’d recommend doing something like this.
JavaScript
<?php
function computeDiscountAndTax($order, $discount, $tax){
$tax = ($tax/100) * ($order - $discount);
$discount = $order > 200 ? ($discount/100) * $order : 0;
return ["discount" => $discount, "tax" => $tax];
}
$results = computeDiscountAndTax(100, 10, 7);
echo "Discount: " . $results['discount'] . "<br />";
echo "Tax: " . $results['tax'] . "<br />";