Menu
Coddy logo textTech

Challenge: Shopping Cart Total

Part of the Logic & Flow section of Coddy's PHP journey — lesson 67 of 68.

challenge icon

Challenge

Easy

You will receive a single input: a JSON string representing an array of shopping cart items.

The input will be a JSON string in this format: [{"name":"Laptop","price":999.99,"quantity":1},{"name":"Mouse","price":25.50,"quantity":2},{"name":"Keyboard","price":75.00,"quantity":1}]

Read the input and decode the JSON string into an array of items. Each item has three properties: name, price, and quantity.

Calculate the total cost of the shopping cart by multiplying each item's price by its quantity, then summing all the results. Use array_reduce() with a custom callback function to calculate this total.

After calculating the total, print it in the following format:

Total: $[amount]

Format the amount to exactly 2 decimal places using number_format().

Input format:

  • A single line containing a JSON string representing the shopping cart items array with keys name, price, and quantity

Expected output: A single line showing the total cost in the format: Total: $[amount] where the amount is formatted to 2 decimal places

Try it yourself

<?php
// Read the JSON input
$input = fgets(STDIN);

// Decode the JSON string into an array
$items = (array)json_decode($input, true);

// TODO: Write your code below to calculate the total using array_reduce()


// Output the result
echo "Total: $" . number_format($total, 2);
?>

All lessons in Logic & Flow