Jump to content

[SOLVED] limiting the loop


almystersv

Recommended Posts

Hi Guys,

 

I am creating a mock up of a stationary ordering system and have a side bar on main products page that shows a snippet of the shopping basket and i want it to show just the top three items in the basket.

 

Here is my code that displays the basket on my products page...

 

<?php
if (isset ($_SESSION['basket'])) 
{
foreach($_SESSION['basket'] as $key => $product)
{ ?>
  <tr>
    <td width="40%"><?php echo $_SESSION['basket'][$key]['productName']?></td>
    <td width="20%">£<?php echo $_SESSION['basket'][$key]['price']?></td>
	<td width="20%" align="center"><?php echo $_SESSION['basket'][$key]['quantity']?></td>
	<td><a href="removefrombasket.php?URN=<?php echo $product['URN']?>">[-]</a></td>
  </tr>
<?php } ?>
</table>
<?php }
else { ?>
No Products Chosen.
<?php }
?>

 

the reason for this is that i have limited space and at current everytime something is added it keeps displaying it on this page, understandably, but I would like to know how I can change it to show just 3.

 

Thanks

Link to comment
Share on other sites

add a counter

 

<?php
if (isset ($_SESSION['basket'])) 
{
  $n = 0;
  foreach($_SESSION['basket'] as $key => $product)
  {
?>
  <tr>
    <td width="40%"><?php echo $_SESSION['basket'][$key]['productName']?></td>
    <td width="20%">£<?php echo $_SESSION['basket'][$key]['price']?></td>
	<td width="20%" align="center"><?php echo $_SESSION['basket'][$key]['quantity']?></td>
	<td><a href="removefrombasket.php?URN=<?php echo $product['URN']?>">[-]</a></td>
  </tr>
<?php
    $n++;
    if($n >= 3) break;
  }
?>
</table>
<?php
}
else { ?>
No Products Chosen.
<?php
}
?>

Link to comment
Share on other sites

in the if >= 3 statement, you can add more code before the break (like printing a more... link)

 

as far as sometimes showing 3, and other times showing all, i would setup a $limit variable in the session to help keep track of which version to show. Then change the if to:

if($limit && $n >= 3){....

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.