Jump to content

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


ab2qik

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.

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.