So I have a for loop that is decreasing...
for ($i=count($array); i>0; $i--;)
{
if(condition)
{DO SOMETHING like print the element in a decreasing manner}
if(enter ending iteration condition here after xth element) break;
}
that pretty much sums up my question. How do I formulate the ending iteration - let's say after 5 elements printed I want to stop the iteration.
$j = 0;
for ($i=count($array); $i>0; $i--)
{
if(condition)
{
DO SOMETHING like print the element in a decreasing manner;
$j++;
}
if($j > 4){
break;
}
}
Try to reverse the count of the loop. Instead of decreasing, try to increase so you will have a count of how many items are being printed.
<?php
for ($i = 0; $i < count($array); $i++)
{
if(condition)
{
/* DO SOMETHING like print the element in a decreasing manner */
}
/* replace (nth) with the needed number */
if($i === (nth)) break;
}
You could set the limit based on the count, like:
$loop_limit = 5;
$array_count = count($array);
$last = $array_count - $loop_limit;
for ($i = $array_count; $i >= $last ; --$i) {
if ( $i == $last ) {
//Do whatever you need at this point
}
//do the normal loop action
}