A closure is an anonymous function that can capture variables from its surrounding scope. It allows you to use variables outside the function inside it.
Click to reveal answer
beginner
How do closures help with array functions like array_map or array_filter?
Closures let you write small, custom functions directly inside array functions to process or filter array elements without defining a separate named function.
Click to reveal answer
intermediate
Explain the use of the 'use' keyword in closures with array functions.
The 'use' keyword lets a closure access variables from the parent scope by copying them into the closure, so you can use external values inside the anonymous function.
A. The closure does not return false for values <= 10, causing unexpected filtering
B. The array_filter function requires a named function, not a closure
C. The array_filter call is missing the array parameter
D. The closure syntax is invalid without a semicolon after return
Solution
Step 1: Analyze closure return behavior
The closure returns true only if value > 10, but returns nothing (null) otherwise.
Step 2: Understand array_filter behavior
array_filter expects explicit boolean returns. Returning implicit null (falsy) for values <=10 removes them but can cause unexpected filtering behavior.
Final Answer:
The closure does not return false for values <= 10, causing unexpected filtering -> Option A
Quick Check:
Closure must return true or false explicitly [OK]
Hint: Always return true or false explicitly in closures for array_filter [OK]
Common Mistakes:
Not returning false explicitly in closure
Thinking closures must be named functions
Missing array parameter in array_filter
5. Given an array $data = [1, 2, 3, 4, 5, 6], how can you use a closure with array_filter and array_map together to get an array of squares of only the odd numbers?