Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear

Stuck with a problem? Got Error? Ask AI support!

Copy Clear
Copy Format Clear
<?php function distributeDiscount($products, $discountAmount) { // Calculate the base discount amount for each product $numProducts = count($products); $baseDiscount = $discountAmount / $numProducts; // Initialize the total discount $totalDiscount = 0; // Loop through each product except the last one for ($i = 0; $i < $numProducts - 1; $i++) { $product = $products[$i]; $product['discount'] = $baseDiscount; $totalDiscount += $baseDiscount; } // Calculate the discount for the last product $lastProduct = $products[$numProducts - 1]; $lastProductDiscount = $discountAmount - $totalDiscount; $lastProduct['discount'] = $lastProductDiscount; // Return the updated array of products return $products; } // Example usage: $products = [ ['name' => 'Product A', 'price' => 100], ['name' => 'Product B', 'price' => 50], ['name' => 'Product C', 'price' => 30], ]; $discountAmount = 70; $productsWithDiscounts = distributeDiscount($products, $discountAmount); // Print the updated array of products with discounts print_r($productsWithDiscounts);
Copy Clear