如何检查变量是否存在,并且在一次扫描中为true


How to check if a variable exists, and is true in one sweep?

这几乎可以肯定是这个问题的重复,但我想我的问题更多的是关于通用惯例/最佳实践,给出了答案。

示例:

if(isset($this->_available[$option]['accepts_argument']) && $this->_available[$option]['accepts_argument']) {
  // do something
}

真难看。但如果我不进行第一次检查,我会得到一个php通知。我应该确保数组键"accepts_argument"始终存在,并且默认为false吗?这样我就可以测试它是否属实,而不是同时测试它是否存在?

我应该不担心丑陋/冗长吗?

我在我的代码中注意到了很多这种模式,只是想知道人们是如何处理它的。如果这很重要的话,我目前正在使用php5.4,但如果5.5+中有一些花哨的东西我可以做,我可以升级它。

感谢

以下是我使用的一个可以帮助您的函数:

 /** todo handle numeric values
 * @param  array  $array      The array from which to get the value
 * @param  array  $parents    An array of parent keys of the value,
 *                            starting with the outermost key
 * @param  bool   $key_exists If given, an already defined variable
 *                            that is altered by reference
 * @return mixed              The requested nested value. Possibly NULL if the value
 *                            is NULL or not all nested parent keys exist.
 *                            $key_exists is altered by reference and is a Boolean
 *                            that indicates whether all nested parent keys
 *                            exist (TRUE) or not (FALSE).
 *                            This allows to distinguish between the two
 *                            possibilities when NULL is returned.
 */
function &getValue(array &$array, array $parents, &$key_exists = NULL)
{
    $ref = &$array;
    foreach ($parents as $parent) {
        if (is_array($ref) && array_key_exists($parent, $ref))
            $ref = &$ref[$parent];
        else {
            $key_exists = FALSE;
            $null = NULL;
            return $null;
        }
    }
    $key_exists = TRUE;
    return $ref;
}

它获取数组中某个元素的值,即使该数组是嵌套的。如果路径不存在,则返回null。魔术

示例:

$arr = [
    'path' => [
        'of' => [
            'nestedValue' => 'myValue',
        ],
    ],
];
print_r($arr);
echo getValue($arr, array('path', 'of', 'nestedValue'));
var_dump(getValue($arr, array('path', 'of', 'nowhere')));