Here’s a simple BMI (Body Mass Index) Calculator in PHP along with an explanation of the code.
This calculator will allow users to input their weight and height, and it will calculate their BMI and categorize the result.
Table of Contents
Project Description
The BMI calculator will:
Allow users to input their weight (in kilograms or pounds) and height (in meters or feet and inches).
Calculate the BMI based on the provided inputs.
Display the BMI value and provide feedback on the user’s health status (e.g., underweight, normal, overweight, or obese).
Complete Code
<?php // Initialize variables $bmi = ""; $bmi_category = ""; $error_message = ""; // Function to calculate BMI function calculateBMI($weight, $height) { return $weight / ($height * $height); // Formula: BMI = weight(kg) / height(m)^2 } // Check if the form has been submitted if (isset($_POST['submit'])) { // Retrieve user input $weight = $_POST['weight']; $height = $_POST['height']; // Validate if the inputs are numeric and positive if (is_numeric($weight) && is_numeric($height) && $weight > 0 && $height > 0) { // Calculate the BMI $bmi = calculateBMI($weight, $height); $bmi = number_format($bmi, 2); // Format the BMI value to 2 decimal places // Determine the BMI category based on the BMI value if ($bmi < 18.5) { $bmi_category = "Underweight"; } elseif ($bmi >= 18.5 && $bmi <= 24.9) { $bmi_category = "Normal weight"; } elseif ($bmi >= 25 && $bmi <= 29.9) { $bmi_category = "Overweight"; } else { $bmi_category = "Obesity"; } } else { $error_message = "Please enter valid positive numbers for weight and height."; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>BMI Calculator</title> </head> <body> <h1>BMI Calculator</h1> <!-- Display any error messages --> <?php if ($error_message): ?> <p style="color: red;"><?php echo $error_message; ?></p> <?php endif; ?> <!-- Form to input weight and height --> <form method="post" action=""> <label for="weight">Enter your weight in kilograms (kg):</label> <input type="text" name="weight" required value="<?php echo isset($weight) ? $weight : ''; ?>"> <br><br> <label for="height">Enter your height in meters (m):</label> <input type="text" name="height" required value="<?php echo isset($height) ? $height : ''; ?>"> <br><br> <button type="submit" name="submit">Calculate BMI</button> </form> <!-- Display the calculated BMI and category if available --> <?php if ($bmi): ?> <h2>Your BMI is: <?php echo $bmi; ?></h2> <h3>You are classified as: <?php echo $bmi_category; ?></h3> <?php endif; ?> </body> </html>
Explanation of the Code
1. Form Submission and Input Handling
if (isset($_POST['submit'])) { $weight = $_POST['weight']; $height = $_POST['height']; }
This block checks if the form has been submitted by the user. It retrieves the values for weight and height from the form using $_POST[‘weight’] and $_POST[‘height’].
2. Input Validation
if (is_numeric($weight) && is_numeric($height) && $weight > 0 && $height > 0) {
This validates that both the weight and height are numeric and greater than zero. If the input values are valid, it proceeds to calculate the BMI; otherwise, an error message is displayed.
3. BMI Calculation
function calculateBMI($weight, $height) { return $weight / ($height * $height); // Formula: BMI = weight(kg) / height(m)^2 }
The calculateBMI() function calculates the BMI using the formula:
BMI= weight (kg) / height (m) 2
The result is formatted to two decimal places using number_format().
4. BMI Category Classification
if ($bmi < 18.5) { $bmi_category = "Underweight"; } elseif ($bmi >= 18.5 && $bmi <= 24.9) { $bmi_category = "Normal weight"; } elseif ($bmi >= 25 && $bmi <= 29.9) { $bmi_category = "Overweight"; } else { $bmi_category = "Obesity"; }
Based on the calculated BMI value, the script classifies the result into one of the four categories:
Underweight: BMI less than 18.5
Normal weight: BMI between 18.5 and 24.9
Overweight: BMI between 25 and 29.9
Obesity: BMI of 30 or greater
5. Displaying the Result and Error Messages
<?php if ($bmi): ?> <h2>Your BMI is: <?php echo $bmi; ?></h2> <h3>You are classified as: <?php echo $bmi_category; ?></h3> <?php endif; ?>
If the BMI has been successfully calculated, the result and the BMI category are displayed.
If an error occurs (e.g., invalid input), the error message will be displayed instead of the result.
6. HTML Form for Input
<form method="post" action=""> <label for="weight">Enter your weight in kilograms (kg):</label> <input type="text" name="weight" required> <br><br> <label for="height">Enter your height in meters (m):</label> <input type="text" name="height" required> <br><br> <button type="submit" name="submit">Calculate BMI</button> </form>
This form allows the user to input their weight and height.
The form uses the POST method to send the data back to the same PHP script for processing.
Two input fields are provided for weight (in kilograms) and height (in meters).
How the BMI Calculator Works
User Input: The user enters their weight in kilograms and height in meters.
Form Submission: When the user clicks the “Calculate BMI” button, the form data is sent to the PHP script via POST.
Validation: The script validates that the weight and height are positive numeric values.
BMI Calculation: The calculateBMI() function calculates the BMI using the formula: BMI= weight (kg) / height (m) 2
Result Display: The script displays the BMI value and the corresponding category (underweight, normal weight, overweight, or obesity).
Potential Improvements
Weight in Pounds: Allow the user to enter their weight in pounds and convert it to kilograms.
Height in Feet/Inches: Allow the user to enter their height in feet and inches and convert it to meters.
Styling: Add CSS for improved appearance and layout.
More Detailed Feedback: Provide more detailed health advice based on the BMI result.
This simple PHP BMI calculator is a great way to practice working with forms, input validation, conditional logic, and basic mathematical operations.