Hello,
If I have an array with say 100 elements.. how can I echo/show the top 5 only for example?
Thank you :)
Hello,
If I have an array with say 100 elements.. how can I echo/show the top 5 only for example?
Thank you :)
for ($index=0; $index < min(5, array_count($arr)); $index++)
{
echo $arr[$index];
}
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).
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