Search code examples
phphtmlarraysformsget

PHP If undefined set default value on GET value


I have the below form where I am putting in a value in my field which is different depending if there is anything to GET or not.

What I have works but I am wondering if there is more efficient way of coding this, as my real form will have around 10 input fields and I don't want to be adding 6 lines of code each time I add a new input field?

        <?php
        if (isset($_GET["name"])) {
            $name = $_GET["name"];
        }
        else {
            $name = 0;
        }

        if (isset($_GET["type"])) {
            $type = $_GET["type"];
        }
        else {
            $type = 0;
        }

        if (isset($_GET["other"])) {
            $other = $_GET["other"];
        }
        else {
            $other = 0;
        }
        ?>


        <input type="text"  name="name" value="<?php echo $name; ?>">
        <input type="text"  name="type"  value="<?php echo $type; ?>">
        <input type="text"  name="other" value="<?php echo $other; ?>">

I have tried to also do

        <?php
            $name = $_GET["name"] ?: 0;
        ?>

This puts in a value of 0 into my form but I get the error Notice: Undefined index: name


Solution

  • Use isset() in the ternary operator:

    $name = isset($_GET["name"]) ? $_GET["name"] : 0;
    

    You get the notice because you evaluate $_GET['name'] directly, without using isset() or empty() wrapper.

    You might prefer to make a resuble function to simply your code:

    function filterThing($key){
        return isset($_GET[$key]) ? $_GET[$key] : 0;
    }
    
    $name = filterThing('name');
    $type = filterThing('type');
    $other = filterThing('other');