If I have an array with say 100 elements.. how can I echo/show the top 5 only for example?
Thank you :)
See LimitIterator and ArrayIterator
$array = range(1,100);
$iterator = new LimitIterator(new ArrayIterator($array), 0, 5);
foreach($iterator as $key => $val) {
echo "$key => $val", PHP_EOL;
}
outputs:
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
One option is to use array_slice()
To show each element followed by a line break:
echo implode("<br>", array_slice($array, 0, 5));
not suitable for arrays containing huge amounts of data because the slice will be a copy, but elegant for normal everyday use.
For a resource-conscious approach, see @Svisstack's answer (And now @Gordon's).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With