Challenge: Shopping Cart Total
Part of the Logic & Flow section of Coddy's PHP journey — lesson 67 of 68.
Challenge
EasyYou 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, andquantity
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
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise7Working with Dates and Times
The 'date()' FunctionUnix Timestamps with 'time()'Intro to the DateTime ObjectFormatting DateTime ObjectsModifying DateTime ObjectsRecap: Date Calculations10Final Challenges
Challenge: Palindrome CheckerChallenge: Character FrequencyChallenge: Shopping Cart TotalChallenge: Unique Item Filter2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting