0
0
PHPprogramming~20 mins

Array map function in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Map Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of array_map with a simple callback
What is the output of the following PHP code?
PHP
<?php
$numbers = [1, 2, 3, 4];
$result = array_map(fn($n) => $n * 2, $numbers);
print_r($result);
?>
AArray ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
BArray ( [1] => 2 [2] => 4 [3] => 6 [4] => 8 )
CArray ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
DArray ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )
Attempts:
2 left
💡 Hint
array_map applies the function to each element and returns a new array with the results.
Predict Output
intermediate
2:00remaining
Using array_map with multiple arrays
What is the output of this PHP code?
PHP
<?php
$a = [1, 2, 3];
$b = [4, 5, 6];
$result = array_map(fn($x, $y) => $x + $y, $a, $b);
print_r($result);
?>
AArray ( [0] => 1 [1] => 2 [2] => 3 )
BArray ( [0] => 5 [1] => 7 [2] => 9 )
CArray ( [0] => 4 [1] => 5 [2] => 6 )
DArray ( [0] => 1 [1] => 7 [2] => 9 )
Attempts:
2 left
💡 Hint
array_map can take multiple arrays and pass corresponding elements to the callback.
🔧 Debug
advanced
2:00remaining
Identify the error in array_map usage
What error does this PHP code produce?
PHP
<?php
$values = [1, 2, 3];
$result = array_map('strtoupper', $values);
print_r($result);
?>
AArray ( [0] => 1 [1] => 4 [2] => 9 )
BFatal error: Call to undefined function strtoupper()
CArray ( [0] => 1 [1] => 2 [2] => 3 )
DWarning: strtoupper() expects parameter 1 to be string, int given
Attempts:
2 left
💡 Hint
strtoupper expects strings, but the array contains integers.
🧠 Conceptual
advanced
2:00remaining
How does array_map handle arrays of different lengths?
Given these arrays, what will be the output of array_map?
PHP
<?php
$a = [1, 2, 3, 4];
$b = [10, 20];
$result = array_map(fn($x, $y) => $x + $y, $a, $b);
print_r($result);
?>
AArray ( [0] => 11 [1] => 22 [2] => 3 [3] => 4 )
BArray ( [0] => 11 [1] => 22 )
CWarning: array_map(): Argument #2 is shorter than Argument #1
DArray ( [0] => 11 [1] => 22 [2] => 13 [3] => 24 )
Attempts:
2 left
💡 Hint
array_map uses NULL for missing elements in shorter arrays.
📝 Syntax
expert
2:00remaining
Which option produces the output: Array ( [0] => 1 [1] => 4 [2] => 9 )?
Select the PHP code snippet that produces the output shown when run.
A
&lt;?php
$nums = [1, 2, 3];
$result = array_map(fn($n) =&gt; $n * 3, $nums);
print_r($result);
?&gt;
B
&lt;?php
$nums = [1, 2, 3];
$result = array_map(fn($n) =&gt; $n + 2, $nums);
print_r($result);
?&gt;
C
&lt;?php
$nums = [1, 2, 3];
$result = array_map(fn($n) =&gt; $n ** 2, $nums);
print_r($result);
?&gt;
D
&lt;?php
$nums = [1, 2, 3];
$result = array_map(fn($n) =&gt; $n - 1, $nums);
print_r($result);
?&gt;
Attempts:
2 left
💡 Hint
The output shows squares of the numbers.