Advertisement
reenadak

convert temperature

Feb 20th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.46 KB | None | 0 0
  1.  /*
  2.     - Temperature Conversion
  3.     - Converts one temperature to another
  4.    
  5.     $from     - The temperature to convert from.
  6.                 => "c" - celsius
  7.                 => "f" - fahrenheit
  8.                 => "k" - kelvin
  9.    
  10.     $to       - The temperature to convert to.
  11.                 => "c" - celsius
  12.                 => "f" - fahrenheit
  13.                 => "k" - kelvin
  14.    
  15.     $value    - The temperature to be converted
  16.     */
  17.  
  18.     function convertTemperature($from, $to, $value)
  19.     {
  20.         $from = strtolower($from);
  21.         $to = strtolower($to);
  22.  
  23.         if(!in_array($from, array("f", "c", "k") )) die("Invalid From value");
  24.         if(!in_array($to, array("f", "c", "k") )) die("Invalid To value");
  25.        
  26.         if (is_numeric($value) || is_double($value))
  27.         {
  28.             // Get input value in degree Kelvin, if($from == "K") then no action required.
  29.             if($from == "c") $value += 273.15;
  30.             if($from == "f") $value = (($value - 32) / 1.8) + 273.15;
  31.             if($value<0) die("Invalid input value entered."); // Validating received value.
  32.  
  33.             // GET converted value, if($to == "K") // No acton required.
  34.             if($to == "c") $value -= 273.15;
  35.             if($to == "f") $value = (($value - 273.15) * 1.8) + 32;
  36.  
  37.             return $value;
  38.         }
  39.         else
  40.         {
  41.             return false;
  42.         }
  43.     }
  44.  
  45. // for example.
  46.     echo convertTemperature("c", "f", 39);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement