7

e.g:

$arr = array('k1'=>1,'k2'=>2,'k3'=>3);

If i want get $arr['k4'] (unexpect index),there is a notice:

Notice: undefined index......

so,can i set a dufalut value for array,like as ruby's hash:

h = {'k1'=>1,'k2'=>2,'k3'=>3}
h.default = 'default'
puts h['k4']

then,i'll get 'default';

2 Answers 2

8

Just do some sort of check to see if it exists:

isset($arr['k4'])?$arr['k4']:'default';

Or make a function for it:

function get_key($key, $arr){
    return isset($arr[$key])?$arr[$key]:'default';
}

//to use it:
get_key('k4', $arr);
Sign up to request clarification or add additional context in comments.

Comments

5

@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'

1 Comment

@Neal: It's not supposed to be dynamic. It's supposed to be for when you have specific keys that you are expecting. Both have valid use-cases...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.