0
0
PHPprogramming~5 mins

Closures in array functions in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Athis
Buse
Cstatic
Dglobal
Which PHP function commonly uses closures to transform array elements?
Aarray_push
Barray_merge
Carray_pop
Darray_map
What type of function is a closure in PHP?
AAnonymous function
BNamed function
CRecursive function
DStatic function
In this code, what is the role of the closure?
array_filter($arr, function($x) { return $x > 10; });
ATo filter elements greater than 10
BTo add elements to the array
CTo sort the array
DTo reverse the array
What happens if you omit the 'use' keyword when trying to access an external variable inside a closure?
AThe variable is automatically global
BThe closure can still access the variable
CYou get an error or undefined variable inside the closure
DThe closure ignores the variable silently
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.