0
0
PHPprogramming~15 mins

Closures as callbacks in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Closures as callbacks
📖 Scenario: You are building a simple PHP program that processes a list of numbers. You want to apply different operations to each number using functions that you can pass around easily.
🎯 Goal: Learn how to create and use closures (anonymous functions) as callbacks in PHP to process an array of numbers.
📋 What You'll Learn
Create an array of numbers
Create a closure (anonymous function) to double a number
Use the closure as a callback to process the array
Print the processed array
💡 Why This Matters
🌍 Real World
Closures as callbacks are useful when you want to pass small pieces of code to functions for flexible processing, like transforming data or filtering lists.
💼 Career
Understanding closures and callbacks is important for PHP developers working with array functions, event handlers, or asynchronous code.
Progress0 / 4 steps
1
Create the numbers array
Create an array called numbers with these exact values: 1, 2, 3, 4, 5.
PHP
Need a hint?

Use square brackets [] to create an array in PHP.

2
Create a closure to double a number
Create a closure called double that takes one parameter $n and returns $n * 2.
PHP
Need a hint?

Use function($n) { return $n * 2; }; to create the closure.

3
Use the closure as a callback to process the array
Use the array_map function with the double closure to create a new array called doubledNumbers.
PHP
Need a hint?

Use array_map($double, $numbers) to apply the closure to each element.

4
Print the processed array
Print the doubledNumbers array using print_r.
PHP
Need a hint?

Use print_r($doubledNumbers); to display the array.