Jump to content

Only display first 10 items from an array


frshjb373

Recommended Posts

I'm trying to use php to echo only the first 10 items of an array.  I have the entire list displaying if there are more than 10 items, but I can't figure out how to display only 10.  Here's the code.  Any help is much appreciated.  Thank you in advance!

<?php 
	if (count($all_machines) > 10) {
		echo '<ul>';
		foreach($all_machines as $machine) {
			echo '<li>' . $machine['name'] . '</li>';
		}
		echo '</ul>';
	} else {
		echo "No machines";
	}
?>

Your code is saying to fetch every result if there are more than ten. Here's another way to approach it.

<?php
// Count up how many are in the array
$all_machines_count=count($all_machines);
// Initialize a counter
$i=0;
// Either way, start the list
 echo '<ul>';
// If there are more than ten results, stop at 10
    if ($all_machines_count) > 10) {
        while($i<10){
            echo '<li>' . $machine[$i]['name'] . '</li>';
           ++$i;
           }
// If there are 10 or fewer results, stop at the last record
        } else {
        while($i<$all_machines_count){
             echo '<li>' . $machine[$i]['name'] . '</li>';
           ++$i;
           }
         }
// Either way, end the list
       echo '</ul>'; 

?>

How about a "for" loop?

 

for ($i 0$i <= 10$i++) 

    {echo "<li>" . $array[$i] . "</li>";}

 

I don't recall, but that might display the first 11 items.  If that is so, simply change "$i <= 10" to "$i 10".

 

Cheers.

xProteuSx,

 

If there are less than 10 items then you'll have "undefined index" problems. This would cure it

echo '<ul>';
$k = min(10, count($array));
for ($i = 0; $i < $k; $i++) {
    echo "<li>" . $array[$i] . "</li>";
}
echo '</ul>';

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.