safely get array element value for defined and undefined indexes-Collection of common programming errors

As far as you only need NULL as “default” value, you can make use of the error suppression operator:

$x = @$array['idx'];

It will prevent warnings. However if you like to allow other default values as well, you can encapsulate the access to an array offset via the ArrayAccess interface:

class PigArray implements ArrayAccess
{
    private $array;
    private $default;

    public function __construct(array $array, $default = NULL)
    {
    $this->array   = $array;
    $this->default = $default;
    }

    public function offsetExists($offset)
    {
    return isset($this->array[$offset]);
    }

    public function offsetGet($offset)
    {
    return isset($this->array[$offset]) ? $this->array[$offset] : NULL;
    }

    public function offsetSet($offset, $value)
    {
    $this->array[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
    unset($this->array[$offset]);
    }
}

Usage:

$array = array_fill_keys(range('A', 'C'), 'default value');
$array = new PigArray($arrayData);
$a     = $array['A'];   # string(13) "default value"
$idx   = $array['idx']; # NULL

Originally posted 2013-11-10 00:11:00.