Dan Rivers
Dan Rivers

Reputation: 173

php - Foreach - Wrapping <li> </li> with two results inside, then repeating.

Working with php - Im trying to run a "foreach" on an array, but i want to wrap every two results in li tags. Output will look like this.

<li>

<div>result 1</div>

<div>result 2</div>

</li>

<li>

<div>result 3</div>

<div>result 4</div>

</li>

<li>

<div>result 5</div>

<div>result 6</div>

</li>

how do i go about doing this?

Thanks!

Upvotes: 3

Views: 5536

Answers (3)

Andrej
Andrej

Reputation: 7504

$count = 0;
foreach ($array as $key=>$value) {
    ++$count;
    if ($count == 1) {
        echo "<li>";
        echo "<div>" . $value."</div>";    
    } else {
        echo "<div>" . $value."</div>";    
        echo "</li>";
        $count = 0;
    }
}

Upvotes: 1

shesek
shesek

Reputation: 4682

$chunks = array_chunk($arr, 2);
foreach ($chunks as $chunk) {
    // $chunk could have either 2 elements, or just one on the last iteration on an array with odd number of elements
    echo '<li>';
    foreach ($chunk as $value) {
        echo '<div>' . $value . '</div>';
    }
    echo '</li>';
}

Upvotes: 9

Fabio Cicerchia
Fabio Cicerchia

Reputation: 679

$results = array(1, 2, 3, 4, 5, 6);
echo "<li>";
foreach($results as $pos => $result) {
    if ($pos > 2 && $pos % 2 == 0) {
        echo "</li>\n<li>";
    }
    echo "<div>result $result</div>";
}
echo "</li>";

or more simply:

$results = array(1, 2, 3, 4, 5, 6);
$max = count($results);
for($i = 0; $i < $max; $i++) {
    echo "<li>";
    echo "<div>result " . $results[$i] . "</div>";
    $i++;
    echo "<div>result " . $results[$i] . "</div>";
    echo "</li>";
}

Upvotes: 1

Related Questions