Iterating over array getting look-ahead items along
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_lookaheads, count($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:
- Relative and absolute paths, in the file system and on the web server.
- PHP error reporting
- Do you really need to check for both isset() and empty() at the same time?
- What's wrong with popular articles telling you that foo is faster than bar?
- MVC in simpler terms or the structure of a modern web-application
- How to get a single player's rank based on the score
- Articles
- Do you abuse the null coalescing operator (and isset/empty as well)?
- Operator precedence or how does 'or die()' work.
- Why should I use prepared statements if escaping is safe?
- Numerical strings comparison
- Do generators really reduce the memory usage?
- How to make Stack Overflow a nice place
- How to debug small PHP programs
Add a comment
Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator's review.
Markdown is now supported:
>
before and an empty line after for a quote