Jump to content

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>';
Edited by Barand
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.