0
0
PHPprogramming~30 mins

Why closures matter in PHP - See It in Action

Choose your learning style9 modes available
Why closures matter in PHP
📖 Scenario: Imagine you are building a simple PHP program to manage a list of tasks. You want to create a way to filter tasks based on their priority using a special function that remembers the priority level you want to filter by. This is where closures in PHP become very useful.
🎯 Goal: You will create a closure in PHP that remembers a priority level and then use it to filter tasks. This will show why closures matter: they let you keep some data inside a function for later use.
📋 What You'll Learn
Create an array called $tasks with specific tasks and their priorities
Create a variable called $priorityFilter to hold the priority level to filter
Create a closure called $filterTasks that uses use to remember $priorityFilter
Use array_filter with $filterTasks to get tasks matching the priority
Print the filtered tasks
💡 Why This Matters
🌍 Real World
Closures help keep some data inside a function, which is useful when you want to create small, reusable pieces of code that remember settings or filters. This is common in web apps, data processing, and event handling.
💼 Career
Understanding closures is important for PHP developers because many modern PHP frameworks and libraries use closures for callbacks, event listeners, and filtering data efficiently.
Progress0 / 4 steps
1
Create the tasks array
Create an array called $tasks with these exact entries: 'Buy groceries' => 'high', 'Clean house' => 'low', 'Pay bills' => 'medium', 'Call mom' => 'high'.
PHP
Need a hint?

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

2
Set the priority filter
Create a variable called $priorityFilter and set it to the string 'high'.
PHP
Need a hint?

Use = to assign the string 'high' to $priorityFilter.

3
Create the closure to filter tasks
Create a closure called $filterTasks that takes one parameter $priority and uses use ($priorityFilter) to remember the $priorityFilter variable. The closure should return true if $priority equals $priorityFilter, otherwise false.
PHP
Need a hint?

Use function($priority) use ($priorityFilter) to create the closure that remembers $priorityFilter.

4
Filter and print the tasks
Use array_filter with $tasks and $filterTasks to create a new array called $filteredTasks. Then print $filteredTasks using print_r.
PHP
Need a hint?

Use array_filter($tasks, $filterTasks) to get tasks with priority 'high'. Then use print_r to display the filtered tasks.