@Neal's answer is good for generic usage, but if you have a predefined set of keys that need to be defaulted, you can always merge the array with a default:
$arr = $arr + array('k1' => null, 'k2' => null, 'k3' => null, 'k4' => null);
that way, if $arr defines any of those keys, it will take precidence. But the default values will be there if not. This has the benefit of making option arrays easy since you can define different defaults for each key.
Edit Or if you want ruby like support, just extend arrayobject to do it for you:
class DefaultingArrayObject extends ArrayObject {
public $default = null;
public function __construct(array $array, $default = null) {
parent::__construct($array);
$this->default = $default;
}
public function offsetGet($key) {
if ($this->offsetExists($key)) {
return parent::offsetGet($key);
} else {
return $this->default;
}
}
}
Usage:
$array = new DefaultingArrayObject($array);
$array->default = 'default';
echo $array['k4']; // 'default'