Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo certain number of elements from PHP Array

Tags:

arrays

php

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

Thank you :)

like image 572
Ahmad Fouad Avatar asked Jun 08 '26 22:06

Ahmad Fouad


2 Answers

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
like image 115
Gordon Avatar answered Jun 10 '26 10:06

Gordon


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

like image 33
Pekka Avatar answered Jun 10 '26 10:06

Pekka