0

I'm a beginner with PHP (and other programming languages).

Currently busy with learning about functions and parameters. I thought I got it, but with running this code I get the error as in the title of this post.. Anyone can tell me what I am doing wrong here?

I tried placing the function on different places or changing the return statement. Also tried to asign the called function to a variable first and then use echo to print out a line with that variable in it. Gave me all the same result...

<?php

    if(isset($_POST["submit"]))
    {
        $length = $_POST["length"];
        $weight = $_POST["weight"];

        echo bmiCalculation($length, $weight);

        if($bmi <= 15) { echo "Life-threatening underweight"; }
        elseif($bmi < 19)   { echo "Underweight"; }
        elseif($bmi <= 25)  { echo "Normal weight"; }
        elseif($bmi < 30)   { echo "Overweight"; }
        elseif($bmi < 35)   { echo "Obese"; }
        elseif($bmi >= 35)  { echo "Morbidly obese"; }  
        
        function bmiCalculation($input1, $input2)
        {
            $bmi = $input2 / ($input1 * $input1); 
            return "Your BMI is: " . round($bmi, 2) . "<br>Status: ";        
        }   
    }
?>
  • 1
    This is a scope issue. `$bmi` exists only inside the function `bmiCalculation` – RiggsFolly Jul 07 '21 at 14:59
  • 1
    _Note_ While its legal to create a function inside an IF, its really not very logical and can catch you out when for some reason the IF is not entered but you still try and call the function – RiggsFolly Jul 07 '21 at 15:00
  • _Also note_ If you define a function inside an IF it will not get defined until that code is reached the first time. This destroys the 2 pass compile ability of the PHP interpreter. So define your function at the top of a script OR at the bottom, either way they will get created before they are ever called. – RiggsFolly Jul 07 '21 at 15:06
  • Thanks @RiggsFolly! I somehow completely missed this! –  Jul 08 '21 at 07:47

0 Answers0