Intro
If I loop in PHP, and know how many times I want to iterate, I usually use the for-loop like this:
for($y=0; $y<10; $y++) {
// ...
}
But lately I have seen someone use the foreach-loop:
foreach (range(1, 10) as $y) {
// ...
}
Now, I found the foreach-loop much more readable and thought about adopt this foreach-construct. But on the other side the for-loop is faster as you can see in the following.
Speed Test
I did then some speed tests with the following results.
Foreach:
$latimes = [];
for($x=0; $x<100; $x++) {
$start = microtime(true);
$lcc = 0;
foreach (range(1, 10) as $y) {
$lcc ++;
}
$latimes[$x] = microtime(true) - $start;
}
echo "Test 'foreach':\n";
echo (float) array_sum($latimes)/count($latimes);
Results after I runnt it five times:
Test 'foreach': 2.2873878479004E-5
Test 'foreach': 2.2327899932861E-5
Test 'foreach': 2.9709339141846E-5
Test 'foreach': 2.5603771209717E-5
Test 'foreach': 2.2120475769043E-5
For:
$latimes = [];
for($x=0; $x<100; $x++) {
$start = microtime(true);
$lcc = 0;
for($y=0; $y<10; $y++) {
$lcc++;
}
$latimes[$x] = microtime(true) - $start;
}
echo "Test 'for':\n";
echo (float) array_sum($latimes)/count($latimes);
Results after I runnt it five times:
Test 'for': 1.3396739959717E-5
Test 'for': 1.0268688201904E-5
Test 'for': 1.0945796966553E-5
Test 'for': 1.3313293457031E-5
Test 'for': 1.9807815551758E-5
Question
What I like to know is what would you prefer and why? Which one is more readable for you, and would you prefer readability over speed?
foreachcase, you are also callingrange(). Try the same thing with an array.