Home » Php » how to set default value for array(php)

how to set default value for array(php)

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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

Answer:

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