Recall & Review
beginner
What is a closure in PHP?
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.
Click to reveal answer
beginner
Example: What does this code output?
$nums = [1, 2, 3];
$factor = 3;
$result = array_map(function($n) use ($factor) { return $n * $factor; }, $nums);
print_r($result); It outputs: Array ( [0] => 3 [1] => 6 [2] => 9 ) because the closure multiplies each number by 3 using the captured $factor variable.
Click to reveal answer
intermediate
Why might you prefer closures in array functions over named functions?
Closures keep the code concise and close to where it's used, improving readability and avoiding cluttering the code with many small named functions.
Click to reveal answer
What keyword allows a closure to access variables from outside its own scope in PHP?
✗ Incorrect
The 'use' keyword imports variables from the parent scope into the closure.
Which PHP function commonly uses closures to transform array elements?
✗ Incorrect
array_map applies a function (often a closure) to each element of an array.
What type of function is a closure in PHP?
✗ Incorrect
Closures are anonymous functions that can capture variables from outside.
In this code, what is the role of the closure?
array_filter($arr, function($x) { return $x > 10; });✗ Incorrect
The closure returns true for elements greater than 10, so array_filter keeps those.
What happens if you omit the 'use' keyword when trying to access an external variable inside a closure?
✗ Incorrect
Without 'use', the closure cannot see variables from outside its scope.
Explain how closures work with array functions in PHP and why the 'use' keyword is important.
Think about how you pass extra data into the anonymous function.
You got /4 concepts.
Describe a simple example of using a closure with array_map to multiply each element by a factor.
Imagine you have a list of numbers and want to multiply each by 3.
You got /4 concepts.