Lee Saxon Lee Saxon - 1 month ago 7
PHP Question

PHP For (certain array keys) loop

Editing this question entirely, for future learners.

I initially asked if a single

while
function could replace the code below. I didn't realize
while
doesn't increment automatically like
foreach
, so no. Great answers below on better solutions using either
array_slice()
or the classic
for
loop.

foreach ($array as $key => $value) {
if ($key < 25) {
echo '<img src="'.$value.'/preview_image.jpg">';
}
}

Answer Source

You would still have to increment the key, plus the key would have to be uniform to work.

Foreach works on the set and is more resilient against gaps in the range. Iterating over a set with for example 1,2 and 4 as keys, works great with foreach.

Another method could be:

for ($i=0;$i<25;$i++) etc 

This checks the end conditions straight away, but does not take gaps into account, which could lead to extra code in the for loop itself.