Bird
Raised Fist0
PHPprogramming~20 mins

Closures in array functions in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Closure Mastery in PHP Arrays
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of array_map with closure capturing variable
What is the output of the following PHP code?
PHP
<?php
$multiplier = 3;
$numbers = [1, 2, 3];
$result = array_map(function($n) use ($multiplier) {
    return $n * $multiplier;
}, $numbers);
print_r($result);
?>
AArray ( [0] => 3 [1] => 6 [2] => 9 )
BArray ( [0] => 1 [1] => 2 [2] => 3 )
CArray ( [0] => 0 [1] => 0 [2] => 0 )
DFatal error: Undefined variable: multiplier
Attempts:
2 left
💡 Hint
Closures can capture variables from the surrounding scope using the 'use' keyword.
❓ Predict Output
intermediate
2:00remaining
Effect of modifying captured variable by reference in closure
What will be the output of this PHP code?
PHP
<?php
$factor = 2;
$numbers = [1, 2, 3];
$result = array_map(function($n) use (&$factor) {
    return $n * $factor;
}, $numbers);
$factor = 5;
print_r($result);
?>
AArray ( [0] => 2 [1] => 4 [2] => 6 )
BArray ( [0] => 5 [1] => 10 [2] => 15 )
CArray ( [0] => 10 [1] => 20 [2] => 30 )
DFatal error: Cannot use variable by reference in closure
Attempts:
2 left
💡 Hint
The closure captures the variable by reference, but array_map applies the function immediately.
🔧 Debug
advanced
2:00remaining
Identify the error in closure used with array_filter
What error does the following PHP code produce?
PHP
<?php
$threshold = 10;
$values = [5, 15, 20];
$filtered = array_filter($values, function($v) {
    return $v > $threshold;
});
print_r($filtered);
?>
AArray ( [0] => 5 [1] => 15 [2] => 20 )
BParse error: syntax error, unexpected '{'
CArray ( [1] => 15 [2] => 20 )
DFatal error: Undefined variable: threshold
Attempts:
2 left
💡 Hint
Variables outside the closure must be imported with 'use' to be accessible inside.
📝 Syntax
advanced
2:00remaining
Syntax error in closure with array_reduce
Which option correctly fixes the syntax error in this PHP code?
PHP
<?php
$numbers = [1, 2, 3];
$sum = array_reduce($numbers, function($carry, $item) {
    $carry += $item
    return $carry;
});
echo $sum;
?>
ARemove the return statement inside the closure
BAdd a comma after '$carry += $item,' inside the closure
CAdd a semicolon after '$carry += $item;' inside the closure
DChange 'function' to 'fn' for arrow function syntax
Attempts:
2 left
💡 Hint
PHP statements must end with semicolons.
🚀 Application
expert
3:00remaining
Count how many elements satisfy a condition using closure
Given the array $data = [2, 7, 4, 9, 3], which option correctly counts how many numbers are greater than 5 using array_filter and a closure?
PHP
<?php
$data = [2, 7, 4, 9, 3];
$count = /* fill in here */;
echo $count;
?>
Aarray_reduce($data, fn($c, $x) => $c + ($x > 5), 0)
Bcount(array_filter($data, fn($x) => $x > 5))
Carray_filter($data, fn($x) => $x > 5)
Dcount(array_map(fn($x) => $x > 5, $data))
Attempts:
2 left
💡 Hint
array_filter returns filtered elements; count counts them.

Practice

(1/5)
1. What is the main purpose of using a closure inside PHP array functions like array_map or array_filter?
easy
A. To define a small, unnamed function that processes array elements inline
B. To declare a global variable accessible inside the array
C. To create a new array without any function
D. To convert arrays into strings automatically

Solution

  1. Step 1: Understand what a closure is

    A closure is a small, unnamed function that can be used directly where needed.
  2. Step 2: Role in array functions

    Closures let you write the logic for processing each array element inline, making code concise and clear.
  3. Final Answer:

    To define a small, unnamed function that processes array elements inline -> Option A
  4. Quick Check:

    Closure = small inline function [OK]
Hint: Closures are small functions used directly inside array calls [OK]
Common Mistakes:
  • Thinking closures declare global variables
  • Confusing closures with array conversion functions
  • Assuming closures create arrays without functions
2. Which of the following is the correct syntax to use a closure with array_filter to keep only even numbers from an array $numbers?
easy
A. array_filter($numbers, function $n { return $n % 2 == 0; });
B. array_filter($numbers, function($n) { return $n % 2 == 0; });
C. array_filter($numbers, function($n) => $n % 2 == 0;);
D. array_filter($numbers, function($n) { $n % 2 == 0; });

Solution

  1. Step 1: Check closure syntax

    Correct closure syntax uses function($param) { return expression; }.
  2. Step 2: Validate each option

    array_filter($numbers, function($n) { return $n % 2 == 0; }); uses correct syntax with return statement. array_filter($numbers, function $n { return $n % 2 == 0; }); misses parentheses. array_filter($numbers, function($n) => $n % 2 == 0;); uses arrow syntax incorrectly. array_filter($numbers, function($n) { $n % 2 == 0; }); lacks return keyword.
  3. Final Answer:

    array_filter($numbers, function($n) { return $n % 2 == 0; }); -> Option B
  4. Quick Check:

    Closure syntax needs parentheses and return [OK]
Hint: Closures need parentheses and return keyword inside curly braces [OK]
Common Mistakes:
  • Omitting parentheses around parameters
  • Using arrow syntax incorrectly in PHP 7+
  • Forgetting to return a value inside closure
3. What will be the output of the following PHP code?
$nums = [1, 2, 3, 4];
$result = array_map(function($x) { return $x * 3; }, $nums);
print_r($result);
medium
A. [0, 3, 6, 9]
B. [1, 2, 3, 4]
C. [3, 6, 9, 12]
D. Syntax error

Solution

  1. Step 1: Understand array_map with closure

    array_map applies the closure to each element, multiplying by 3.
  2. Step 2: Calculate each element

    1*3=3, 2*3=6, 3*3=9, 4*3=12, so result is [3, 6, 9, 12].
  3. Final Answer:

    [3, 6, 9, 12] -> Option C
  4. Quick Check:

    Multiply each by 3 = [3,6,9,12] [OK]
Hint: array_map applies closure to each element and returns new array [OK]
Common Mistakes:
  • Expecting original array unchanged
  • Confusing array_map with array_filter
  • Thinking output is a string, not array
4. Identify the error in this PHP code using a closure with array_filter:
$values = [10, 15, 20];
$filtered = array_filter($values, function($v) {
  if ($v > 10) {
    return true;
  }
});
print_r($filtered);
medium
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

  1. Step 1: Analyze closure return behavior

    The closure returns true only if value > 10, but returns nothing (null) otherwise.
  2. 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.
  3. Final Answer:

    The closure does not return false for values <= 10, causing unexpected filtering -> Option A
  4. 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?
hard
A. array_filter(fn($x) => $x % 2 !== 0, array_map($data, fn($x) => $x * $x));
B. array_filter(array_map($data, fn($x) => $x * $x), fn($x) => $x % 2 !== 0);
C. array_map(array_filter($data, fn($x) => $x % 2 !== 0), fn($x) => $x * $x);
D. array_map(fn($x) => $x * $x, array_filter($data, fn($x) => $x % 2 !== 0));

Solution

  1. Step 1: Filter odd numbers first

    Use array_filter with closure to keep only odd numbers: fn($x) => $x % 2 !== 0.
  2. Step 2: Map squares of filtered numbers

    Apply array_map with closure to square each filtered number: fn($x) => $x * $x.
  3. Step 3: Combine calls correctly

    Pass filtered array as second argument to array_map, so filtering happens before mapping.
  4. Final Answer:

    array_map(fn($x) => $x * $x, array_filter($data, fn($x) => $x % 2 !== 0)); -> Option D
  5. Quick Check:

    Filter odds then map squares [OK]
Hint: Filter first, then map to transform filtered results [OK]
Common Mistakes:
  • Reversing order of array_map and array_filter
  • Passing arguments in wrong order
  • Using array_map or array_filter with wrong parameter order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard