Why array functions matter in PHP - Performance Analysis
When working with arrays in PHP, the way we use built-in array functions can change how fast our code runs.
We want to see how these functions affect the time it takes to finish tasks as the array grows.
Analyze the time complexity of the following code snippet.
$array = range(1, $n);
// Using array_map to double each value
$result = array_map(fn($x) => $x * 2, $array);
// Using foreach to double each value
$result2 = [];
foreach ($array as $value) {
$result2[] = $value * 2;
}
This code doubles each number in an array using two methods: a built-in function and a manual loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing the entire array to process each element once.
- How many times: Exactly once for each element, either inside array_map or foreach loop.
As the array size grows, the number of operations grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: Doubling the array size roughly doubles the work done.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items in the array.
[X] Wrong: "Using array_map is slower because it's a function call for each item."
[OK] Correct: Both array_map and foreach loop go through each item once, so their time grows the same way with input size.
Understanding how built-in array functions work helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we used a nested loop inside array_map or foreach? How would the time complexity change?"