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

前端 未结 4 439
暗喜
暗喜 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:21

    If you need to make sure certain keys exist then you can create a default array and merge in your input (or whatever). That way all necessary keys will exist and they will be updated if possible:

    $defaults = array(
        'foo' => '',
        'bar' => ''
    );
    
    $data = array_merge($defaults, $someOtherArray);
    

    Docs for array_merge(): http://php.net/array_merge

    I find this helpful when taking into consideration check-boxes on a HTML form that may or may not show up in $_GET or $_POST.

    Note that this process expects string array keys, not numeric ones. See the documentation for clarification.

提交回复
热议问题