Php – how to set default value for array(php)

php

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

Best Solution

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);