0

I am building a menu with pricing loaded by calling array keys. Menu displays but I can't get the values to show in the price section.

I loaded an associative array and am looking to call its values from inside a function. I've declared global scope, and am using heredoc to add the values to the table. I'm also attempting to call the printMenu() function by encapsulation. Prices are showing inside the menu ONLY when the code has NOT been placed inside function.

Don't know what's wrong here. Help please!

    printMenu();

    $plain = array(
      "small" => "3.50",
      "medium" => "6.25",
      "large" => "8.00"
    );

    function printMenu() {
      global $plain;
      print <<<HERE
        <table>
          <tr>
           <th>&nbsp;</th>
           <th class = "pSize">Small</th>
           <th class = "pSize">Med</th>
           <th class = "pSize">Large</th>
          </tr>
          <tr>
           <th>Plain</th>
           <td class ="price">$plain[small]</td>
           <td class ="price">$plain[medium]</td>
           <td class ="price">$plain[large]</td>
          </tr>
        </table>
    HERE;
    }

1 Answers1

1

You have to declare your variable before you're calling a function with your global variable:

$plain = array(
  "small" => "3.50",
  "medium" => "6.25",
  "large" => "8.00"
);

printMenu();

Also maybe you will consider to set this variable as argument in your function. Check this:

function printMenu($argName) {
   var_dump($argName);
}

$plain = array(
  "small" => "3.50",
  "medium" => "6.25",
  "large" => "8.00"
);

printMenu($plain);
speccode
  • 1,562
  • 9
  • 11
  • I considered it, but I have four arrays (i.e. $plain, $vegetarian, $pepperoni, $hawaiian). I provided only one array as solving the problem for one SHOULD be the solution for four, entered into one table. Correct? AND THANK YOU. First response to one of my posts. I think I'm a stackoverflow believer, except for the fact that I can't upvote your solution. Hoping to contribute an answer...one day =/ – Jovan Laurencio Oct 27 '13 at 00:15
  • I don't know if I get you right but check `array_merge` on docs. You can't upvote my answer as you're new guy here. For now you can only check answers in your question as "accepted". – speccode Oct 27 '13 at 06:24