Is there an idiomatic way to get a potentially undefined key from an array in PHP?

前端 未结 4 411
暗喜
暗喜 2021-01-18 04:36

PHPeoples, I\'m so tired of doing this

$value = isset($arr[$key]) ? $arr[$key] : null;

Or this

$value = array_key_exists($k         


        
4条回答
  •  清歌不尽
    2021-01-18 05:23

    It's already a built-in function if using $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, you can use:

    $value = filter_input(INPUT_GET, $key);
    

    Plus it does much more. Optional filters make it handy if you also want validate or sanitize filters in the same assignment.

    Returns - Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.

提交回复
热议问题