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";