7

So, I'm learning PHP and I keep getting "Warning: Undefined array key" in $GET_["fname"] and $GET_["age"]:

<main>

    <form action="inputs.php" method="get">
        Name: 
        <br/>
        <input type="text" name="fname">
        <br/>
        Age:
        <br/>
        <input type="number" name="age">
        <br/>
        <input type="submit" name="submit">

    </form>
        <br/>
        Your name is <?php echo $_GET["fname"]; ?>
        <br/>
        Your age is <?php echo $_GET["age"]; ?>

</main>
mintfudge
  • 81
  • 1
  • 1
  • 4
  • 1
    One the "first call" of the page the parameters are not set, that's why the error shows up. Check first if they are set using [isset](https://www.php.net/manual/en/function.isset.php), then output them. (You can remove the `action` parameter if the page you submit to is the same page as the one your form is on) – brombeer Jan 06 '21 at 21:34
  • Thx for the action tip. :)) – mintfudge Jan 06 '21 at 21:52

1 Answers1

11

I'll assume you want to know how to get rid of this error message.

The first time you load this page you display a form and $_GET is empty (that's why it is triggering warnings). Then you submit the form and the fname and age parameters will be added to the url (because your form's method is 'get').

To resolve your issue you could wrap the two lines inside some if-statement, for example:

<?php if(isset($_GET['fname']) && isset($_GET['age'])): ?>
        <br/>
        Your name is <?php echo $_GET["fname"]; ?>
        <br/>
        Your age is <?php echo $_GET["age"]; ?>
<?php endif; ?>
Joshua Angnoe
  • 1,010
  • 4
  • 11
  • I'm learning from a youtube course that was recorded in 2018, could be because it was an old version of php? In the video the teacher don't show any "isset" and his code still works, but mine doesn't. – mintfudge Jan 06 '21 at 21:53
  • I doubt that the tutorial code works without warnings/errors. Turn off error reporting/display and errors are not shown (bad practice), but your $_GET parameters will nevertheless _not_ be set if the form isn't submitted – brombeer Jan 06 '21 at 21:56
  • Got it. Thank you so much for the help @brombeer – mintfudge Jan 06 '21 at 22:06
  • Yes, since php 8.0 (latest version) this type of errors are presented as warnings, before this they where classified as notices and notices are often times ignored. – Joshua Angnoe Jan 06 '21 at 22:08
  • Thank you @JoshuaAngnoe. – mintfudge Jan 07 '21 at 17:55