0

I have a process which works just fine on it's own but fails to render any info from within a function.

This works:

if ($totalRows_menu > 0) {
    echo "<ul>";
    while($row_menu = mysql_fetch_array($menu)) {
        echo "<li>" . $row_menu['m3menu_item'] . "</li>";
    }
    echo "</ul>";
    }

but this doesn't:

function m3menu()
{
if ($totalRows_menu > 0) {
    echo "<ul>";
    while($row_menu = mysql_fetch_array($menu)) {
        echo "<li>" . $row_menu['m3menu_item'] . "</li>";
    }
    echo "</ul>";
    }
}
echo m3menu();
  • 1
    How about just `m3menu();` instead of `echo m3menu();`? – Sakthi Kumar Aug 08 '13 at 11:32
  • 3
    `$totalRows_menu` and `$menu` are not available in the function. Read up on variable scopes. http://php.net/manual/en/language.variables.scope.php Keep in mind that the use of global variables is generally not recommended. – user254875486 Aug 08 '13 at 11:33
  • Lex - Your comment threw me. I am quite a novice. I have to declare within the function? – mikemcmonagle Aug 08 '13 at 11:34
  • I note this is marked as duplicate by some members. Had I known the term "variable scopes" and usage chances are I would not have need to ask the question. I did search but sometimes you can't search when you don't know what the solution is. Easy on the learners please. – mikemcmonagle Aug 09 '13 at 14:08

1 Answers1

1

As Lex says your variables are not available in the scope of the function. You can either pass them into the function when you call it, or you can use global

Also, your function is echoing rather than returning the HTML so there is no need for echo m3menu(); you should just call the function like m3menu();, or you could return the HTML from the function and then echo out the value.

Method 1

function m3menu( $totalRows_menu, $menu )
{
    if ($totalRows_menu > 0) {
        echo "<ul>";
        while($row_menu = mysql_fetch_array($menu)) {
            echo "<li>" . $row_menu['m3menu_item'] . "</li>";
        }
        echo "</ul>";
    }
}

m3menu($totalRows_menu, $menu);

Method 2

function m3menu()
{
    global $totalRows_menu;
    global $menu;

    if ($totalRows_menu > 0) {
        echo "<ul>";
        while($row_menu = mysql_fetch_array($menu)) {
            echo "<li>" . $row_menu['m3menu_item'] . "</li>";
        }
        echo "</ul>";
    }
}

m3menu();
MajorCaiger
  • 1,893
  • 1
  • 12
  • 18