0

I'm trying to use what I've learned in PHP in this BMI calculator. I checked the code for errors in a PHP syntax checker and it's clean, but I'm getting an error when I render the page in a browser. The error is where $bmi is declared.

Any tips to writing better code is appreciated.

      <form class="" action="index.php" method="post">
      Name:  <input type="number" name="name" value=""><br>
      Age:  <input type="number" name="age" value=""><br>
      Height:  <input type="number" name="height" value=""><br>
      Weight:  <input type="number" name="weight" value=""><br>
      <input type="submit" name="sumbit" value="Submit">
      </form>


      <?php
      $name = $_POST["name"];
      $age = $_POST["age"];
      $height = $_POST["height"];
      $weight = $_POST["weight"];

      if ($weight && $height) {

          function greeting() {
             $bmi = $weight / ($height * $height);####Error is in this line
            echo "Hello $name, your age is $age. You weigh $weight kg and your height in meters is $height <br> Your BMI is $bmi";
            #$GLOBALS["height"] = $height;
            #$GLOBALS["weight"] = $weight;
          }
            greeting();
        }
      ?>
      <br><br>
      <?php
        if ($bmi < 18) {
         echo "You are underweight.";
       } elseif ( $bmi >= 18 && $bmi < 25 ) {
         echo "You are normalweight.";
       } elseif ($bmi > 25) {
         echo "You are overweight.";
       }
       ?>
user3783243
  • 5,368
  • 5
  • 22
  • 41
tceriksen
  • 35
  • 2
  • What is the error and on what line does it happen? – David Dec 30 '20 at 16:24
  • 2
    Variable/function scope. Weight and height exist outside of the function. If you want to use them, you need to pass them in – aynber Dec 30 '20 at 16:24
  • 3
    Generally you don't put a named function inside an if statement. Function normally go at the end of your main logic to keep things clean. – Jason K Dec 30 '20 at 16:27
  • Thanks for the comments, people. I moved the weight and height vars into the function and now it works. – tceriksen Dec 30 '20 at 22:12

0 Answers0