'Return something specific in case an array's key does not exist
is there a way to make an array return the a "default value" if the requested key was not set?
Example:
$arr = array("a_set_key" => "A Value");
$arr = the_function_I_need($arr, "n/a");
echo $arr['any_key']; // Shall return "n/a"
echo $arr['a_set_key']; // Shall return "A Value"
Solution 1:[1]
There isn't any native way to do and use it as you want but there are other ways, the most usual is to use isset which you could use like this:
echo isset($arr['any_key']) ? $arr['any_key'] : 'n/a';
echo $arr['any_key'] ?? 'n/a'; // php 7.0+
Or you can create special class which act like that, for example like this:
class the_function_I_need implements ArrayAccess
{
private $arr;
private $naval;
public function __construct($arr, $naval) {
$this->arr = $arr;
$this->naval = $naval;
}
public function offsetExists($offset) {
return isset($this->arr[$offset]);
}
public function offsetGet($offset) {
//return isset($this->arr[$offset]) ? $arr[$offset] : $this->naval; // pre 7.0 php
return $this->arr[$offset] ?? $this->naval; // php 7.0+
}
public function offsetSet($offset, $value) {
$this->arr[$offset] = $value;
}
public function offsetUnset($offset) {
unset($this->arr[$offset]);
}
}
$arr = array("a_set_key" => "A Value");
$arr = new the_function_I_need($arr, "n/a");
echo $arr['any_key']; // Shall return "n/a"
echo $arr['a_set_key']; // Shall return "A Value"
Notice that the $arr variable is no longer an array but object.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kazz |
