Reputation: 99
I am unable to generate same number of </ul>
as <ul>
in the following code:
<?php
$array=array("item1","item2","item3");
for ($i=0;$i<count($array);$i++)
{
if($i<count($array)-1)
{
echo '<li><span>'.$array[$i].'</span><ul>';
}
else
{
echo '<li><span>'.$array[$i].'</span>';
}
}
for ($i=0;$i<count($array);$i++)
{
echo '</ul></li>';
}
?>
The code is generating uneven number of <li><ul>
and </ul></li>
. Please tell me where I am going wrong?
Upvotes: 1
Views: 42
Reputation: 801
Try This:
$array=array("item1","item2","item3");
echo '<ul>';
for ($i=0;$i<count($array);$i++)
{
echo '<li><span>'.$array[$i].'</span></li>';
}
echo '</ul>;
Upvotes: 0
Reputation: 1967
With if($i<count($array)-1)
you check if $i is smaller than the length - 1.
That check isn't performed in the second loop. So the first one actually performs as many steps as the second one but only writes in all but the last iteration.
Upvotes: 0
Reputation: 1
This is a minor error. In your second for statement change $i<count($array);
to $i<count($array)-1;
.
So your final code will be:
<?php
$array=array("item1","item2","item3");
for ($i=0;$i<count($array);$i++)
{
if($i<count($array)-1)
{
echo '<li><span>'.$array[$i].'</span><ul>';
}
else
{
echo '<li><span>'.$array[$i].'</span>';
}
}
for ($i=0;$i<count($array)-1;$i++)
{
echo '</ul></li>';
}
?>
Upvotes: 1