Sakhar
Sakhar

Reputation: 55

How to "pause" a foreach loop to output few HTML lines

So let's say I have an array with key => values I want to output in 2 different HTML lists. Is it possible to do so by using the same loop?

<ul>
    // Start foreach and get keys and values**
    <li>$key</li>
    // "Pause" foreach to output the next couple of lines once
</ul>
<ul>
    // Resume foreach
    <li>$value</li>
    // End foreach
</ul>

The output should be

Upvotes: 0

Views: 279

Answers (3)

Peter Chaula
Peter Chaula

Reputation: 3711

To iterate through the array :

foreach(**array_chunk($array, 3, false) as $container**){


                echo '**<div><ul>**';

   foreach($container as $val){

             echo '<li> ' . $val[] . ' </li>';

}

          echo "**</ul></div>**";
}

Upvotes: 0

Peter Chaula
Peter Chaula

Reputation: 3711

you could use array_chunk($array, 3, false); Then iterate through the sub_arrays into the differrnt lists

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

Think your looking for something like this:

<?php

    $array = array("k1" => "v1", "k2" => "v2", "k3" => "v3");
    $keys = "";
    $values = "";

    foreach($array as $k => $v) {
        $keys .= "<li>" . $k . "</li>";
        $values .= "<li>" . $v . "</li>";
    }

    echo "<ul>" . $keys . "</ul>";
    echo "<ul>" . $values . "</ul>";

?>

Output:

  • k1
  • k2
  • k3

  • v1
  • v2
  • v3

Upvotes: 2

Related Questions