How to set default value for array (php)

eg:

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

If I want to get $ arr ['k4'] (uncertainty index), there is a notification:

 Notice: undefined index...... 

So, can I set the dufalut value for the array, for example, as a ruby ​​hash symbol:

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

then I will get 'default';

+7
source share
2 answers

Just do a check to see if it exists:

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

Or create a function for it:

 function get_key($key, $arr){ return isset($arr[$key])?$arr[$key]:'default'; } //to use it: get_key('k4', $arr); 
+8
source

@ 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']; // 'default' 
+5
source

All Articles