0
0
PHPprogramming~15 mins

Array reduce function in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Array reduce function
📖 Scenario: You are working on a simple shopping cart system. You have a list of prices for items a customer wants to buy.
🎯 Goal: You will use PHP's array_reduce function to calculate the total price of all items in the cart.
📋 What You'll Learn
Create an array called prices with the exact values: 10, 20, 30, 40
Create a variable called initial and set it to 0
Use array_reduce with a callback function named sum that adds two numbers
Store the result of array_reduce in a variable called total
Print the value of total
💡 Why This Matters
🌍 Real World
Calculating totals from lists of numbers is common in shopping carts, billing systems, and data analysis.
💼 Career
Understanding how to use array functions like <code>array_reduce</code> helps you write cleaner and more efficient PHP code in real projects.
Progress0 / 4 steps
1
Create the prices array
Create an array called prices with the exact values 10, 20, 30, and 40.
PHP
Need a hint?

Use square brackets [] to create the array and separate values with commas.

2
Set the initial value
Create a variable called initial and set it to 0.
PHP
Need a hint?

Just assign 0 to a variable named initial.

3
Use array_reduce to sum prices
Use array_reduce with a callback function named sum that takes two parameters and returns their sum. Store the result in a variable called total. Use $prices as the array and $initial as the initial value.
PHP
Need a hint?

Define a function sum that adds two numbers. Then call array_reduce with $prices, the function name as a string, and $initial.

4
Print the total price
Print the value of the variable total.
PHP
Need a hint?

Use print($total); to show the total price.