0
0
PHPprogramming~20 mins

Closures in array functions in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Closures in array functions
📖 Scenario: You have a list of product prices in an online store. You want to apply a discount to some products based on their price.
🎯 Goal: Use a closure (anonymous function) with PHP's array_filter and array_map functions to select products above a certain price and apply a discount.
📋 What You'll Learn
Create an array called prices with the exact values: 100, 50, 200, 150, 80
Create a variable called discount_threshold and set it to 100
Use array_filter with a closure to select prices greater than discount_threshold
Use array_map with a closure to apply a 10% discount to the filtered prices
Print the resulting discounted prices array
💡 Why This Matters
🌍 Real World
Online stores often need to apply discounts to products based on price or other conditions. Using closures with array functions helps write clean and reusable code.
💼 Career
Understanding closures and array functions is important for PHP developers working on e-commerce sites, data processing, and backend logic.
Progress0 / 4 steps
1
Create the prices array
Create an array called prices with these exact values: 100, 50, 200, 150, 80.
PHP
Need a hint?

Use square brackets [] to create the array with the exact numbers inside.

2
Set the discount threshold
Create a variable called discount_threshold and set it to 100.
PHP
Need a hint?

Just assign the number 100 to the variable $discount_threshold.

3
Filter prices above the threshold
Use array_filter with a closure to create a new array called filtered_prices that contains only prices greater than discount_threshold. Use function($price) use ($discount_threshold) as the closure.
PHP
Need a hint?

The closure needs to access $discount_threshold using use keyword.

4
Apply discount and print results
Use array_map with a closure to create a new array called discounted_prices by applying a 10% discount to each price in filtered_prices. Then print discounted_prices using print_r.
PHP
Need a hint?

Multiply each price by 0.9 to apply a 10% discount. Use print_r to display the array.