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

前端 未结 13 1776
抹茶落季
抹茶落季 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:27

    Sadly that's the only way to do it. But there are approaches for dealing with larger arrays. For instance something like this:

    $required = array('myvar', 'foo', 'bar', 'baz');
    $missing = array_diff($required, array_keys($_GET));
    

    The variable $missing now contains a list of values that are required, but missing from the $_GET array. You can use the $missing array to display a message to the visitor.

    Or you can use something like that:

    $required = array('myvar', 'foo', 'bar', 'baz');
    $missing = array_diff($required, array_keys($_GET));
    foreach($missing as $m ) {
        $_GET[$m] = null;
    }
    

    Now each required element at least has a default value. You can now use if($_GET['myvar'] == 'something') without worrying that the key isn't set.

    Update

    One other way to clean up the code would be using a function that checks if the value is set.

    function getValue($key) {
        if (!isset($_GET[$key])) {
            return false;
        }
        return $_GET[$key];
    }
    
    if (getValue('myvar') == 'something') {
        // Do something
    }
    

提交回复
热议问题