foreach() error handling - how do make it do nothing?

Posted by Jared on Stack Overflow See other posts from Stack Overflow or by Jared
Published on 2010-05-02T22:27:45Z Indexed on 2010/05/02 22:37 UTC
Read the original article Hit count: 305

Filed under:
|
|

Hey all,

This should be very basic, but I am a little stumped!

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 don't have data in the them, so I get a

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

If I add (array) to $header like this: foreach( (array)$header as $headers ), It no longer gives me the error, but it just displays the $header as the $headers (i.e. Home - Home, Instead of Home - nothing).

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

© Stack Overflow or respective owner

Related posts about php

Related posts about error-handling