PHP: Fastest way to handle undefined array key

后端 未结 8 1659
梦如初夏
梦如初夏 2020-12-08 07:13

in a very tight loop I need to access tenthousands of values in an array containing millions of elements. The key can be undefinied: In that case it shall be legal to return

8条回答
  •  半阙折子戏
    2020-12-08 07:41

    There are two typical approaches to this.

    1. Define defaults for an undefined key.
    2. Check for undefined key.

    Here is how to perform the first and as little code as possible.

    $data = array_merge(array($key=>false),$data);
    return $data[$key];
    

    Here is how to perform the second.

    return isset($data[$key]) ? $data[$key] : false;
    

提交回复
热议问题