0

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

  • Key 1
  • Key 2
  • Key 3
  • Value 1
  • Value 2
  • Value 3

3
  • no, the only way to do it in a single loop, would be to save the second <li> array into a varaible, and after the firt loop its over, output it Commented Nov 14, 2014 at 23:00
  • @RicardoGarzaV.you should turn that comment into an answer, of course adding in the details. Commented Nov 14, 2014 at 23:02
  • @RicardoGarzaV. could we write your comment starting with "yes" ? Commented Nov 14, 2014 at 23:02

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Can you elaborate please?
0

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>**";
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.