3

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!

3 Answers 3

9
$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>';
}
0
1
$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>";
}
1
  • 2
    This is going to have the same problem as some of the other posts, you need to check for a valid value in case there are odd # of elements, and if it's the last (and odd) one, close the html tags.
    – ldg
    Aug 24, 2011 at 22:03
1
$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;
    }
}
2
  • 1
    you're missing a "$" sign on count and this will result in an unclosed li on an odd count.
    – ldg
    Aug 24, 2011 at 22:24
  • actually, those were two separate issues :p
    – ldg
    Aug 25, 2011 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.