Jump to content

Loop is dislayed with empty li's between filled li's


Recommended Posts

Hello,

 

Got problems displaying a list within a loop. It dislays an empty li between filled li's as seen in frebug. Any way to avoid this? Thankyou.

 

<style type="text/css">

      ul {margin: 0; padding: 0;}

      li {margin: 0.5em; padding: 0; list-style: none;}

</style>

 

$prices = array('Tyres' => 125.00, 'Oil' => 5.50, 'Sparkplugs' => 0.50);

echo '<ul>';

    while (list ($key, $value) = each($prices)) {

      echo '<li>'.$key. ' - ' .$value.'<li>';

    }

echo '</ul>';

jl5501 got the solution, but why would you use WHILE, LIST and EACH when a simple FOREACH loop will do???  You should also try to use descriptive variable names. $key and $value tells yo nothing of what the values actually are except that they probably came from an array. May not be an issue when writing the code, but it will save tons of time when you have to make changes later on. I'd also suggest separating the LOGIC from the OUTPUT. Put the PHP code to generate the content at the top of the page and output the content at the bottom:

 

<?php

$prices = array('Tyres' => 125.00, 'Oil' => 5.50, 'Sparkplugs' => 0.50);

$priceList = "<ul>\n";
foreach($prices as $desc => $price)
{
    $priceList .= "<li>{$desc} - {$price}<li>\n";
}
$priceList .= "</ul>\n";

?>
<html>
<body>

Price list:<br />
<?php echo $priceList; ?>

</body>
</html>

Thankyou for the tips mjdamato.

 

I am testing out loops(and other code) before using in real enviroment. Sure enough foreach was simpler to use compared with the solution posted. It was tested after foreach. Your other points i would definietly bear in mind for real case use. I think next time i post test code i will make this effort.

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.