How can PHP arrays be effectively used to calculate prices based on quantity thresholds?
To calculate prices based on quantity thresholds using PHP arrays, you can create an array where the keys represent the quantity thresholds and the values represent the corresponding prices. Then, you can iterate through the array to find the correct price based on the quantity input.
// Define quantity thresholds and corresponding prices
$priceList = [
1 => 10,
5 => 8,
10 => 5,
20 => 3
];
// Function to calculate price based on quantity
function calculatePrice($quantity, $priceList) {
$price = 0;
foreach ($priceList as $threshold => $priceValue) {
if ($quantity >= $threshold) {
$price = $priceValue;
}
}
return $price * $quantity;
}
// Calculate price based on quantity input
$quantity = 15;
$totalPrice = calculatePrice($quantity, $priceList);
echo "Total price for $quantity items is: $totalPrice";
Keywords
Related Questions
- What are some best practices for efficiently calculating roots in PHP scripts?
- Are there any specific PHP functions or methods that can be used to convert a date from one format to another for database storage and sorting purposes?
- What are the potential pitfalls of not properly checking database query results in PHP?