Iterating over array getting look-ahead items along

  1. Comments

A simple task but for some reason I liked it, after all the small optimizations I made

So we need to loop over array taking a limited number of loop-ahead items as well. If there are no more items, we should start from the beginning.

<?php
// always make such numbers configurable
$num_lookaheads 5;

// test array
$images = [1,2,3,4];
// limit the number of lookaheads if array is too small
$limit min($num_lookaheadscount($images));

foreach (
$images as $position => $value)
{
    
// current item
    
echo $value,"\n";

    
// getting look-aheads 
    // taking the missing items from the beginning
    
$beginning 0;
    for(
$i 1$i $limit$i++) {
        
$ahead $images[$position $i] ?? $images[$beginning++];
        echo 
"    "$ahead,"\n";
    }
}

Related articles: