How can PHP be effectively used to iterate through each row of data, calculate prices, and display the total sum in a web application?
To iterate through each row of data, calculate prices, and display the total sum in a web application using PHP, you can use a loop to go through each row of data, calculate the price for each item, and keep a running total of the sum. Finally, display the total sum on the webpage.
<?php
// Sample data array
$data = [
['item' => 'Apple', 'price' => 1.50],
['item' => 'Banana', 'price' => 0.75],
['item' => 'Orange', 'price' => 0.90]
];
$total = 0;
// Iterate through each row of data
foreach ($data as $row) {
// Calculate the price for each item
$item_price = $row['price'];
// Add the item price to the total sum
$total += $item_price;
// Display the item and its price
echo $row['item'] . ': $' . number_format($item_price, 2) . '<br>';
}
// Display the total sum
echo '<br>Total: $' . number_format($total, 2);
?>