PHP: Check if variable exist but also if has a value equal to something

前端 未结 13 1773
抹茶落季
抹茶落季 2020-12-01 13:46

I have (or not) a variable $_GET[\'myvar\'] coming from my query string and I want to check if this variable exists and also if the value corresponds to somethi

13条回答
  •  青春惊慌失措
    2020-12-01 14:20

    Thanks Mellowsoon and Pekka, I did some research here and come up with this:

    • Check and declare each variable as null (if is the case) before start to use (as recommended):
    !isset($_GET['myvar']) ? $_GET['myvar'] = 0:0;
    

    *ok this one is simple but works fine, you can start to use the variable everywhere after this line

    • Using array to cover all cases:
    $myvars = array( 'var1', 'var2', 'var3');
    foreach($myvars as $key)
        !isset($_GET[$key]) ? $_GET[$key] =0:0;
    

    *after that you are free to use your variables (var1, var2, var3 ... etc),

    PS.: function receiving a JSON object should be better (or a simple string with separator for explode/implode);

    ... Better approaches are welcome :)


    UPDATE:

    Use $_REQUEST instead of $_GET, this way you cover both $_GET and $_POST variables.

    !isset($_REQUEST[$key]) ? $_REQUEST[$key] =0:0;
    

提交回复
热议问题