Calculate BMI(Body Mass Index) using PHP program
Contents
BMI calculator:
Body mass index (BMI) is a measure of body fat based on height and weight that applies to adult men and women.
Formula for BMI :
BMI Categories:
Underweight = <18.5
Normal weight = 18.5–24.9
Overweight = 25–29.9
Obesity = BMI of 30 or greater
Input to the program is height and weight in JSON
1 2 3 4 |
{ "ht":172, "wt":75 } |
PHP program to calculate BMI:
The JSON string contains the height in centimeters and weight in Kgs. The json_decode function is used in the program to converts the JSON string to PHP array.The height and weight variables gets the corresponding value from the array.
The height is divided by 100 that converts the value from centimeters to meters.Then we are applying BMI formula to get the BMI categories.Finally we are validating the BMI value and returns the corresponding message as a output.The json_encode function is used in the last step to converts the PHP array to JSON string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php $input = $_REQUEST["input"]; $phpData = json_decode($input); $height = $phpData->ht; $weight = $phpData->wt; $heightInMs = $height/100; $bmi = $weight/($heightInMs*$heightInMs); $message = ""; if($bmi < 18.5) { $message = "You are underweight."; } else if($bmi >=18.5 && $bmi <= 24.9) { $message = "Congrats!!! You have normal weight."; } else if($bmi >24.9 && $bmi <=29.9) { $message = "You are overweight."; } else { $message = "Be careful!!! You are obese."; } $output = array( "bmi"=>$bmi, "message"=>$message ); echo json_encode($output); ?> |
Output :
1 2 3 4 |
{ "bmi":24.9, "message":Congrats!!! You have normal weight. } |
Recommended Articles