tags:

views:

31

answers:

3

Hello,

If I have an array with say 100 elements.. how can I echo/show the top 5 only for example?

Thank you :)

+2  A: 
for ($index=0; $index < min(5, array_count($arr)); $index++)
{
    echo $arr[$index];
}
Svisstack
+1 for the classic approach
Gordon
+3  A: 

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).

Pekka
+1 for creativity :)
Gordon
+4  A: 

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
Gordon
+1 for SPL. The syntax feels a bit long-winded for the case at hand but makes sense. Out of curiosity, do you know how do the Iterators work memory-wise? Do they work with references, or will line 2 create a copy containing the first five elements (thus occupying additional memory?) Maybe worth a separate question though
Pekka
@Pekka though I don't know the exact implementation details in C, I'm pretty sure they work by reference. They are basically stacked decorators. The `LimitIterator` keeps track of the position it currently is on and if that exceeds the set upper bound it will end the iteration.
Gordon
+1 for fresh PHP5 solution
Svisstack