Question

I need to wrap my html output with <ul> tags.
Using modulus i can start the opening tags (every 4th) using

if( $i==0 || $i % 4==0 )

but for the closing </ul> i need a pattern of 3, 7, 11, 15, 19 etc..
here is my attempt if ( $i!=0 && (($i-1) % 4 == 0 || $i==$max-1) )

full code

$str = '';
$i = 0;
$max = count($value['title']);
foreach ($value['title'] as $key2){

        //if( $i==0 || $i==4 || $i==8 || $i==12 || $i==16 ) 
        if( $i==0 || $i % 4==0 )
            $str .= "<ul>";

        $str .= "<li><a href='#'>$key2</a></li>";

        if( $i==3 || $i==7 || $i==11 || $i==15 || $i==19 || $i==$max-1) 
        //if ( $i!=0 && (($i-1) % 4 == 0 || $i==$max-1) )
        //if( $i!=0 || $i % 3==1  || $i==$max-1) 
            $str .= "</ul>";

        $i++;
    }
echo $str;

after posting the question, i got it by changing the minus to a plus if ( $i!=0 && (($i+1) % 4 == 0 || $i==$max-1) )

Était-ce utile?

La solution 2

Something like this

$value['title'] = range(0, 100);
$max = count($value['title']);
$i = 0;
$count = 4;
$str = '';
foreach ($value['title'] as $key2)
    {
    if ($i % $count == 0)
        $str .= "<ul>" . PHP_EOL;

    $str .= "<li><a href='#'>$key2</a></li>" . PHP_EOL;

    if ($i % $count == $count - 1 || $i == $max - 1)
        $str .= "</ul>" . PHP_EOL;
    $i++;
    }

echo $str;

http://3v4l.org/f6cAl

Autres conseils

I prefer to use to use implodes on arrays myself, but this will do things the way you were heading.

echo '<ul>';
foreach ( $array as $key => $value ) {
    echo "<li><a href='#'>$value</a></li>";
    if ( 3 === $key % 4 ) {
        echo '</ul><ul>';
    }
}
echo '</ul>';

I don't like this method because it means when the array has a multiple of four items there will be an empty ul tag. Could make a difference or not, but I think its sloppy.

Instead my I suggest:

$list = '';
foreach ( $array as $key => $value ) {
    $list  .="<li><a href='#'>$value</a></li>";
    if ( 3 === $key % 4 ) {
        echo "<ul>$list</ul>";
        $list = '';
    }
}

if ( $list ) {
    echo "<ul>$list</ul>";
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top