0

I'm a novice at this, and I am trying to write a simple program on PHP where a user can input the temperature in F, press Submit, and receive the answer in C. However I am getting the following warning message (only when I load the page):

Warning: Undefined array key "Fahrenheit"

I am assuming it's because the $_GET value has not been assigned yet. However, I can't figure out how to fix it.

I also know it's not a very clean program. I tried to add RESET to the page and I got more error messages. But one thing at the time: how do I solve the above error? Here's my code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Converter</title>
</head>
<body>
    Enter temperature in Fahrenheit:
    <form method = "get">
        <input type = "number" name ="fahrenheit">
    <br>
        <input type = "submit" value = "Submit">
<p>
    </form>
<?php

$f = $_GET["fahrenheit"];
$c = round(($f-32)*(5/9),2);
?>
</p>

<p>
    <?php
    echo "The temperature in Celcius is: $c";
    ?>
    
</p>

</body>
</html>
  • 1
    Make sure that the array key exists before you try to use it. – aynber Jul 26 '22 at 18:50
  • `if(!empty($_GET["fahrenheit"])){` before `$f = $_GET["fahrenheit"];`. likely close it after that `echo` line. – user3783243 Jul 26 '22 at 18:54
  • You can simply add an `@` before the `$_GET` to suppress warnings. Or use the `??` operator: `$_GET['fahrenheit'] ?? 0` - this operator is simular to use the `empty()` function. Or even code an `if` to avoid show the message before submit the form. – Matheus Jul 26 '22 at 18:54
  • On the first load of your page, `$f` is trying to access `$_GET['fahrenheit']`, but you haven't provided a value yet... There's lots of ways to handle this (see the comments or the linked question). If you don't understand the comments, then you'll need to look into some coding tutorials on how to handle these types of cases, including both basic PHP and HTML syntax; there's a number of issues in your question. – Tim Lewis Jul 26 '22 at 18:55
  • Thank you! I used the first suggestion with the IF statement and got it working – Yuri Lazzeretti Jul 26 '22 at 19:01

0 Answers0