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";
	}
?>
Link to comment
Share on other sites

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>'; 

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.