How to echo certain number of elements from PHP Array
If I have an a开发者_高级运维rray 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).
for ($index=0; $index < min(5, count($arr)); $index++)
{
echo $arr[$index];
}
精彩评论