Reputation: 41
I have an array in php, and I want to print the elements of the array, 15 at a time, from (n-15). Like, if I have 100 elements in an array, I want to print it 85-100,70-84,55-70,, etc.,
I've tried the loop
for( $j = sizeof($fields)-16; $j < sizeof($fields); ) {
for ( $i = $j ; $i < $i+16 ; $i++ ) {
echo $fields[$i];
echo "<br>";
}
$j=$j-16;
}
but, this prints only the first iternation, i.e 85-100, and goes into an infinite loop.
Where am i going wrong? Help!
Upvotes: 0
Views: 77
Reputation: 5037
In PHP 5.3, you can do this:
<?php
$fields = range(1, 100);
foreach (array_chunk(array_reverse($fields, true), 15, true) as $i => $chunk) {
echo 'Group ' . $i . ":<br/>\n";
$chunk_rev = array_reverse($chunk, true);
array_walk($chunk_rev, function($value) {
echo "$value<br/>\n";
});
}
See the demo.
Upvotes: 1
Reputation: 131841
foreach (array_reverse(array_chunk($fields, 15)) as $chunk) {
foreach ($chunk as $field) {
echo $field . '<br />';
}
}
Upvotes: 2
Reputation: 1003
Think about the loop termination condition.
If $j is being decremented and $j starts off lower than the comparison value, $j will never be greater than the comparison value, so the loop will never terminate.
Upvotes: 0