0
0
PHPprogramming~30 mins

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

Choose your learning style9 modes available
Array filter function
📖 Scenario: You work in a fruit store. You have a list of fruits with their prices. You want to find only the fruits that cost more than 2 dollars.
🎯 Goal: Build a PHP program that filters an array of fruits to keep only those with prices greater than 2 dollars using the array_filter function.
📋 What You'll Learn
Create an associative array called fruits with exact entries: 'apple' => 3, 'banana' => 1, 'cherry' => 5, 'date' => 2, 'elderberry' => 4
Create a variable called price_limit and set it to 2
Use array_filter with a callback function that keeps fruits with price greater than price_limit
Print the filtered array using print_r
💡 Why This Matters
🌍 Real World
Filtering arrays is common when you want to select only certain data from a list, like filtering products by price in an online store.
💼 Career
Understanding how to filter arrays helps in data processing tasks, backend development, and working with APIs that return lists of items.
Progress0 / 4 steps
1
Create the fruits array
Create an associative array called fruits with these exact entries: 'apple' => 3, 'banana' => 1, 'cherry' => 5, 'date' => 2, 'elderberry' => 4
PHP
Need a hint?

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

2
Set the price limit
Create a variable called price_limit and set it to 2
PHP
Need a hint?

Use the = sign to assign the value 2 to price_limit.

3
Filter fruits by price
Use array_filter with a callback function that keeps fruits with price greater than price_limit. Store the result in a variable called expensive_fruits
PHP
Need a hint?

Use an anonymous function with use ($price_limit) to access the variable inside the callback.

4
Print the filtered fruits
Print the expensive_fruits array using print_r
PHP
Need a hint?

Use print_r($expensive_fruits); to display the filtered array.