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';
Initializing an Array with default values To initialize an Array with default values in Java, the new keyword is used with the data type of the Array The size of the Array is then placed in the rectangular brackets. int[] myArr = new int[10]; The code line above initializes an Array of Size 10.
PHP lets you create 2 types of array: Indexed arrays have numeric indices. Typically the indices in an indexed array start from zero, so the first element has an index of 0 , the second has an index of 1 , and so on.
When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
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);
@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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With