Foreach () error handling - how to do this doing nothing?

It should be very simple, but I'm a little confused!

Here is my array:

$menu = array(
  'Home',

  'Stuff'=>array(
    'Losta Stuff',
    'Less Stuff',
    'Ur moms stuff',
    'FAQ'
 ),
  'Public Works'

);

      

Here is my logic:

echo "<ol>\n";
foreach( (array)$menu as $header )
{
  echo '  <li><b>'.$header."</b><br />\n";
 echo '  <ol>';
  foreach( (array)$header as $headers )
  {
    echo '    <li>'.$headers.".</li>\n";
  }
  echo '  </ol>';
}
echo "</ol>\n";

      

As you can see, Home and Public Works have no data in them, so I get

Warning: Invalid argument supplied for foreach() in test.php on line ##

      

If I add (array)

in $header

like this:, foreach( (array)$header as $headers )

it no longer gives me an error, but it just displays $header

as $headers

(that is, Home is Home, instead of Home is nothing).

Basically, if the data is empty, I want it to do nothing!

+2


a source to share


2 answers


You have to check if the current element you are trying to use echo

is an array that can be made with is_array

and then act accordingly. Something like the following might do the trick.



<?php 

$menu = array(
    'Home',
    'Stuff'=>array(
        'Losta Stuff',
        'Less Stuff',
        'Ur moms stuff',
        'FAQ'
    ),
    'Public Works'
);

echo "<ol>\n";
foreach($menu as $menuName => $header )
{
    if (!is_array($header))
    {
        echo '  <li><b>'.$header."</b><br />\n";
    }
    else
    {
        echo "<li><b>$menuName</b><ol>";
        foreach($header as $headers )
        {
            echo '    <li>'.$headers.".</li>\n";
        }
        echo "</ol></li>";
    }
}
echo "</ol>\n";

      

+2


a source


I see something like this:

// your old menu was using keys for headers on "submenus" only
// this one uses keys for headers for everything
$menu = array(
  'Home'=>'Home',   
  'Stuff'=>array(
    'Losta Stuff',
    'Less Stuff',
    'Ur moms stuff',
    'FAQ'
  ),
  'Public Works' => 'Public Works',    
);
echo "<ol>\n";
foreach( (array)$menu as $header => $items )
{
  echo '  <li><b>'.$header."</b>";
  if (is_array($items)) {
    echo "<br />\n";
    echo '  <ol>';
    foreach( $items as $subhead )
    {
      echo '    <li>'.$subhead.".</li>\n";
    }
    echo '  </ol>';
  }
}
echo "</ol>\n";

      



Using is_array to determine if there are additional options under the current menu.

+2


a source







All Articles