@ The short-term answer is good for general use, but if you have a predefined set of keys that are needed by default, you can always combine an array with a default value:
$arr = $arr + array('k1' => null, 'k2' => null, 'k3' => null, 'k4' => null);
thus, if $arr
defines any of these keys, it will make a difference. But the defaults will be there if not. This makes it easy to select arrays, since you can define different default values ββfor each key.
Change If you need ruby ββtype support, just extend the 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; } } }
Using:
$array = new DefaultingArrayObject($array); $array->default = 'default'; echo $array['k4'];
ircmaxell
source share