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

尝试检查嵌套元素的存在性:它是好的php吗?,php,Php,考虑以下形式的数组: $parent = [ 'children' => [ 'visible' => true, 'items' => ['petro', 'johano', 'karlo'] ] ]; 我需要检查$parent['children']['items']是否有一些元素 我知道可以按如下方式进行: function has_children($parent) { if (!isset($parent['children'])) re

考虑以下形式的数组:

$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;
}
但我更愿意这样做,例如:

function has_children($parent) {
  try {
    $parent['children']['items'][0];
    return true;
  } catch (Exception $e) {
    return false;
  }
}
这在php中是安全且良好的做法,还是有一些缺点?

您可以使用
empty()
函数来显示数组是否为空。 不建议尝试捕捉

使用此代码:

if (!empty($parent['children'])){
    if (!empty($parent['children'])){
        return true;
    }
}
return false;

如果期望数组具有以零开头的数字索引,则可以使用:

function has_children($parent) {
  return isset($parent['children']['items'][0]);
}
isset
并不真正“取消引用”数组,因此在检查是否存在
$parent['children']['items']
之前,无需检查是否存在
$parent['children']['items']


尝试访问元素并捕获异常是否是一个好主意——这取决于,但很可能不是,这不是一个好主意。
异常会带来额外的性能开销,并且它们在语义上表示异常情况,如果只是检查空性,则不会出现这种情况

你试过运行那个代码吗?除了语法错误之外,它不会以这种方式工作:正如您在中看到的,访问无效数组键只会生成一个通知,而不是异常。所以没有任何东西会被抓到

这与
返回相同!空($parent['children'])&&!空($parent['children'])
My bad,我想我写下几行代码是不会失败的。我现在已经修好了。我应该更深入地检查一下手册中的
isset
,第一个示例中描述了一个类似的情况。谢谢你指出这一点!