Is there a way to simplify this function by using say filter_input

50 views Asked by At
function valueFromGetOrPost($parameter)
{
    $shvalue=NULL;
    if ($_GET[$parameter])
    {
        $shvalue=$_GET[$parameter];
    }
    else if (isset($_POST[$parameter]))

    {
        $shvalue=$_POST[$parameter];
    }
    return $shvalue;

}

say by using filter_input

Basically the code check whether a parameter exist either in GET or POST. And then return the value of the parameter.

I think this must be so common it should be there by some built in function already

3

There are 3 answers

1
Pavel Štěrba On BEST ANSWER

Use $_REQUEST (documentation).

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.

So your code will look like:

function valueFromGetOrPost($parameter)
{
    $shvalue=NULL;
    if ($_REQUEST[$parameter])
    {
        $shvalue=$_REQUEST[$parameter];
    }
    return $shvalue;

}
0
prettyfly On

You could use fast return to simplify it a bit, i.e

function valueFromGetOrPost($parameter){

    $shvalue=NULL;

    if (isset($_GET[$parameter])){
         return $_GET[$parameter];
    } else if (isset($_POST[$parameter])){
         return $_POST[$parameter];
    }
}

Or, you could use a ternary operator, since you're returning NULL anyway if neither are set:

function valueFromGetOrPost($parameter){

 $shvalue = (isset($_GET[$parameter]) ? $_GET[$parameter] : $_POST[$parameter]);

 return $shvalue;

}
0
Cvetan Mihaylov On

Here is my proposal, using the filter_input() function:

function valueFromGetOrPost($parameter)
{
    $value = ($getValue = filter_input(INPUT_GET, $parameter))
        ? $getValue
        : filter_input(INPUT_POST, $parameter);

    return ($value) ? $value : NULL;
}