代码之家  ›  专栏  ›  技术社区  ›  etuardu

尝试检查嵌套元素的存在性:它是好的php吗?

php
  •  2
  • etuardu  · 技术社区  · 6 年前

    考虑窗体中的数组:

    $parent = [
      'children' => [
        'visible' => true,
        'items' => ['petro', 'johano', 'karlo']
      ]
    ];
    

    我需要检查一下 $parent['children']['items']

    function has_children($parent) {
      if (!isset($parent['children'])) return false;
      if (!isset($parent['children']['items'])) return false;
      if (!is_array($parent['children']['items'])) return false;
      if (count($parent['children']['items']) == 0) return false;
      return true;
    }
    

    但我更愿意这样做 EAFP 方式,例如:

    function has_children($parent) {
      try {
        $parent['children']['items'][0];
        return true;
      } catch (Exception $e) {
        return false;
      }
    }
    

    这在php中是安全且良好的做法,还是有一些缺点?

    3 回复  |  直到 6 年前
        1
  •  4
  •   Alex Shesterov    6 年前

    function has_children($parent) {
      return isset($parent['children']['items'][0]);
    }
    

    isset $parent['children'] 在检查是否存在 $parent['children']['items'] 等等


    异常会带来额外的性能开销,并且 表明 如果你只是在检查空虚,那就不是了。

        2
  •  0
  •   mahradbt    6 年前

    empty() 显示数组是否为空的函数。

    使用此代码:

    if (!empty($parent['children'])){
        if (!empty($parent['children'])){
            return true;
        }
    }
    return false;
    
        3
  •  0
  •   Nico Haase    6 年前

    https://3v4l.org/dqGn8 ,访问无效的数组键只会生成通知,而不是异常。所以没有什么东西会被抓住