0
0
PHPprogramming~10 mins

Array map function in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Array map function
Start with array
Pick first element
Apply callback function
Store result in new array
More elements?
YesPick next element
No
Return new array
The map function takes each element of an array, applies a function to it, and collects the results into a new array.
Execution Sample
PHP
<?php
$numbers = [1, 2, 3];
$squares = array_map(fn($n) => $n * $n, $numbers);
print_r($squares);
?>
This code squares each number in the array and prints the new array.
Execution Table
StepCurrent ElementCallback AppliedResult StoredNew Array State
111 * 1 = 11[1]
222 * 2 = 44[1, 4]
333 * 3 = 99[1, 4, 9]
4No more elements--[1, 4, 9]
💡 All elements processed, map returns new array [1, 4, 9]
Variable Tracker
VariableStartAfter 1After 2After 3Final
numbers[1, 2, 3][1, 2, 3][1, 2, 3][1, 2, 3][1, 2, 3]
current elementN/A123N/A
resultN/A149N/A
squares[][1][1, 4][1, 4, 9][1, 4, 9]
Key Moments - 2 Insights
Why does the original array 'numbers' not change after using array_map?
array_map creates a new array with the results and does not modify the original array, as shown in the variable_tracker where 'numbers' stays the same.
What happens if the callback function returns a different type than the input?
The new array will contain the returned values exactly as produced by the callback, regardless of type, because array_map stores the callback results directly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the 'Result Stored' at step 2?
A2
B4
C1
D9
💡 Hint
Check the 'Result Stored' column in row 2 of the execution_table.
At which step does the map function finish processing all elements?
AStep 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look for the step where 'No more elements' appears in the 'Current Element' column.
If the callback function was changed to return $n + 1, what would be the 'New Array State' after step 3?
A[1, 2, 3]
B[1, 4, 9]
C[2, 3, 4]
D[0, 1, 2]
💡 Hint
Consider how adding 1 to each element changes the array values in the variable_tracker.
Concept Snapshot
array_map(callback, array) applies callback to each element
Returns a new array with results
Original array stays unchanged
Callback can be any function or closure
Useful for transforming arrays easily
Full Transcript
The PHP array_map function takes an array and a callback function. It applies the callback to each element in the array one by one. Each result is stored in a new array. The original array remains unchanged. After all elements are processed, the new array is returned. For example, squaring each number in [1, 2, 3] produces [1, 4, 9]. This process is stepwise: pick element, apply function, store result, repeat until done.