How can you calculate the total price by multiplying the price and quantity for each item in a PHP array?
To calculate the total price by multiplying the price and quantity for each item in a PHP array, you can loop through the array and perform the multiplication for each item. You can then sum up the results to get the total price.
// Sample array of items with price and quantity
$items = [
['name' => 'Item 1', 'price' => 10, 'quantity' => 2],
['name' => 'Item 2', 'price' => 15, 'quantity' => 3],
['name' => 'Item 3', 'price' => 20, 'quantity' => 1]
];
$totalPrice = 0;
foreach ($items as $item) {
$totalPrice += $item['price'] * $item['quantity'];
}
echo "Total Price: $" . $totalPrice;
Keywords
Related Questions
- How can PHP be used to pass values from dropdown menus to another page using POST method?
- In the code snippet, what are the implications of not using curly braces for single-line if-else statements, and how does it impact the code execution?
- What are the potential pitfalls of using relative paths instead of absolute paths when handling file uploads in PHP?