How can PHP code be optimized to handle complex price allocation based on weight ranges for multiple packages?
To optimize PHP code for handling complex price allocation based on weight ranges for multiple packages, you can create a function that takes the weight of each package as input and calculates the corresponding price based on the weight range. You can use arrays to store the weight ranges and corresponding prices, then iterate through them to determine the appropriate price for each package.
function calculatePrice($weights) {
$priceRanges = [
['min' => 0, 'max' => 5, 'price' => 10],
['min' => 6, 'max' => 10, 'price' => 15],
['min' => 11, 'max' => 15, 'price' => 20]
];
$totalPrice = 0;
foreach($weights as $weight) {
foreach($priceRanges as $range) {
if($weight >= $range['min'] && $weight <= $range['max']) {
$totalPrice += $range['price'];
break;
}
}
}
return $totalPrice;
}
$weights = [3, 8, 12];
$totalPrice = calculatePrice($weights);
echo "Total price for the packages: $totalPrice";
Keywords
Related Questions
- What are the potential pitfalls of using AJAX to load individual documents automatically on a webpage?
- What best practices should be followed when handling objects returned by imap functions in PHP?
- What is the equivalent function to mysql_insert_id() in MySQL for retrieving the last inserted ID in PHP?