PHP program to Convert Fahrenheit to Celsius

This script is basically apt for School / College students or Newbies who are willing to do the same kind of script which they learned from C programming.

All of us know Basic C program learners should be gone through this kind of programs pretty well, Such as Convert Fahrenheit to Celsius, Addition, Multiplication, etc.,

So, This tutorial is about to teach you a similar kind of Program “Convert Fahrenheit to Celsius” in PHP.

The formula is pretty simple:

<?php

$celsius = ($fahrenheit - 32)*5/9;

?>

This is not a Console program, PHP is a web programming language. So, to get the input, you should always use HTML Web Form.

Let’s see the entire script. Well, read the comments to understand what is happening:

Code Snippet (with comments):

 <?php

 //get the value from the form after hit the enter button
 if($_POST){
    //method="post" so we have to use $_POST
    //get the value from input field
    $fahrenheit = $_POST['fahrenheit'];
    //fahrenheit to celsius formula
    $celsius = ($fahrenheit - 32)*5/9;
 }
 ?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Convert Fahrenheit to Celsius in PHP</title>
    </head>
    <body>
        <form action="" method="post">
        Fahrenheit: <input type="text" name="fahrenheit" /><br />
        <?php 
        //show the celsius after hit the enter button and the calculation
        if(isset($celsius)){
            echo "Celsius = ".$celsius;
        }
        ?>
       </form>
    </body>
</html>

Code Snippet (without comments):

 <?php
 if($_POST){
    $fahrenheit = $_POST['fahrenheit'];
    $celsius = ($fahrenheit - 32)*5/9;
 }
 ?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Convert Fahrenheit to Celsius in PHP</title>
    </head>
    <body>
        <form action="" method="post">
        Fahrenheit: <input type="text" name="fahrenheit" /><br />
        <?php 
        if(isset($celsius)){
            echo "Celsius = ".$celsius;
        }
        ?>
       </form
    </body>
</html>

I have given “with Comments” and “without Comments”, you can take any one of the above code and paste it in your favorite editor then run the script. Enjoy the Day!

1 thought on “PHP program to Convert Fahrenheit to Celsius”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top