I am using a foreach() loop to generate a menu.

I want to specify after N items, to stop clean at the end.

the code looks something like this....

$menu = array(
array("item1"=>"thing1", "itempic"=>"photo"),
array("item1"=>"thing2", "itempic"=>"photo2"),
);

foreach ($menu as $stuff) {
echo "Click <a href=#".$stuff['item1'].">".$stuff['photo']."</a><br>";
}

I jjust need to display the first N things... then stop. The idea is a "highlights" menu. A list of highlights (a large list) and to display "just a few" kind of deal.

just before drawing out the page, i'll use shuffle() on the $menu array so it will be somewhat random.

Ideas on how to do this ?

    well the for() loop is specifically designed for that....

    or you could try looking the continue; and break; commands

      thanks!

      looked up the BREAK command.

      ended up doing something like this....

      $counter = 0;
      
      $stuff = array(
      array( ... )
      )
      
      foreach ($stuff as $thing) {
      ...
      
      if ($counter == 12) {
      break;
      }
      
      }
      
      

      so using something like that, after 12 runs thru the stuff in the { } , it stops.

      worked great!

        you know, i started there... it looked like more code to me... i believe the simple way was to use the arbitrary $counter variable.

        I seem to recall looking at the array_rand stuff and freaking out on possibly having to re-write more than i wanted to.

        adding the "control" code at the top and bottom of my existing code was easier to me i guess. 😃

              $menu = array(
              array("item1"=>"thing1", "itempic"=>"photo"),
              array("item1"=>"thing2", "itempic"=>"photo2"),
              );
          $submenu = array_rand($menu,12);
              foreach ($submenu as $menu_key) {
          $stuff=$menu[$menu_key];
              echo "Click <a href=#".$stuff['item1'].">".$stuff['photo']."</a><br>";
              }
          

          I agree. Two more lines? That's a killer.

            Write a Reply...