SoFunction
Updated on 2025-03-10

PHP foreach, while performance comparison

Foreach operates on a copy of the array (by copying the array), while while operates by moving the internal indicators of the array. Generally, logic believes that while should be faster than foreach (because foreach first copy the array in when it starts executing, while while directly moves the internal indicators.), but the result is just the opposite.
What is performed in the loop is an array "read" operation, and foreach is faster than while:
Copy the codeThe code is as follows:

foreach ($array as $value) {
echo $value;
}
while (list($key) = each($array)) {
echo $array[$key];
}

What is performed in the loop is an array "write" operation, and while is faster than foreach:
Copy the codeThe code is as follows:

foreach ($array as $key => $value) {
echo $array[$key] = $value . '...';
}
while (list($key) = each($array)) {
$array[$key] = $array[$key] . '...';
}

Summary: It is usually believed that foreach involves value copying, which will definitely be slower than while, but in fact, if you just read arrays in a loop, then foreach is very
Fast, this is because the replication mechanism adopted by PHP is "reference counting, copying on write", that is, even if a variable is copied in PHP, the original form is fundamentally
It is still in the form of reference. Only when the content of the variable changes will real copy appear. The reason for this is to save memory consumption, and it also improves
The efficiency of replication. In this way, it seems that foreach's efficient reading operation is not difficult to understand. In addition, since foreach is not suitable for handling array write operations, we can come up with a link
In most cases, the code for doing array writing operations similar to foreach ($array as $key => $value) should be replaced with while (list($key) =
each($array)). The speed difference generated by these techniques may not be obvious in small projects, but in large projects like frameworks, a request will often involve several requests.
If there are hundreds, thousands or tens of thousands of array cycles, the difference will be significantly magnified.