“面向对象”的方法:
你可以创建自己的ArrayAccess实现,它返回一个默认值(null为例),如果关键你正在寻找不存在。最简单的方法是扩大现有ArrayObject类:
class MyArray extends ArrayObject {
public function offsetGet($offset) {
if(!$this->offsetExists($offset)) {
return null; // or some default value
}
return parent::offsetGet($offset);
}
}
然后用这个来代替array():
$arr = new MyArray();
$arr['y'] = "I'm ok";
echo $arr['x']; // not set, default value (null) is returned.
echo $arr['y']; // prints "I'm ok"
程序方法:
你可以定义一个方法,该方法安全从您的阵列中获得价值:
function safeGet($array, $key, $default = null){
if(!is_array($array) && !$array instanceof ArrayAccess){
throw new InvalidArgumentException('$array must be an array');
}
return isset($array[$key]) ? $array[$key] : $default;
}
然后简单地访问使用这种方法你的价值观:
$arr = array();
$arr['z'] = "I'm ok";
echo safeGet($arr, 'x'); // tries to access $arr['x']. prints null by default.
echo safeGet($arr, 'y', 'default'); // tries to access $arr['y']. prints 'default'.
echo safeGet($arr, 'z'); // key exists, prints "I'm ok".