Question

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

Was it helpful?

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');

OTHER TIPS

If someone is interested, using this small method you can also define the default value if GET key is not found or it's not an integer:

//?foo=ABC&x=40

function tryGetInt($key, $def = 0){
    return isset($_GET[$key]) && is_numeric($_GET[$key]) ? $_GET[$key] : $def;
}

$value1 = tryGetInt("foo"); //value1 = 0;
$value2 = tryGetInt("bar",20); //value2 = 20
$value3 = tryGetInt("x",20); //value3 = 40

Try this :

$input_values = array('name','type','other');

foreach(input_values as $value){
   $$value = isset($_GET[$value]) ? $_GET[$value] : 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top