Beginner php “Warning: Undefined array key”

Total
0
Shares

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>

Solution

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; ?>

Source: StackOverflow.com

Leave a Reply

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