Warning
Do not do either of these two things:
$array['index'] = $array['index'] ?: $default;
function default_value(&$var, $default) {
if (empty($var)) {
$var = $default;
}
}
default_value($array['index'], $default);
Both will raise errors due to an undefined index (both first attempt getting the value at the index first) if the index is not set. This is a small thing, but even if you have error reporting AND logging turned off, the error is raised, is built, and propagates through the stack before it is checked if there is anywhere to report the error. And thus, simply doing something that CAN raise an error, incurs a performance hit.
Keep this in mind, because this goes for all Error Types (Notices, Warnings, etc), and in large apps can be a big deal. To avoid this you must use a function that does not raise an error on a missing index, like isset($array['index'])
or empty($array['index'])
, and not use the shortened ternary form.
Try a function like:
function apply_default(Array &$array, $path, $default) {
// may need to be modified for your use-case
preg_match_all("/\[['\"]*([^'\"]+)['\"]*\]/",$path,$matches);
if(count($matches[1]) > 0) {
$destinaion =& $array;
foreach ($matches[1] as $key) {
if (empty($destinaion[$key]) ) {
$destinaion[$key] = array();
}
$destinaion =& $destinaion[$key];
}
if(empty($destinaion)) {
$destinaion = $default;
return TRUE;
}
}
return FALSE;
}
$was_applied = apply_default($array,
"['with a really long name']['and multiple']['indexes']",
$default_value);
This doesn't raise errors, and will create the path if it does not exist. It also benefits from consolidating the logic to set defaults in one place, rather than if
s everywhere.
As mentioned elsewhere, the other option is to:
if(empty($array['key'])) {
$array['key'] = $default;
}
Which is just as good, and probably more performant.
However, all that said, ideally this should only be handled in the consuming service. If the value is empty, the consumer (whether a view or another client [like javascript]) should be allowed to make this choice on it's own. As, in actuality, the semantic data is empty for the model. How this is handled should be up to the consumer it's self, ie, if this is going to a template/view, the conditional should be handled during display. If it is sent as JSON, the client should be able to make the choice.
You are asking about styles, that is probably the most important. The best style is, if you are providing data to a client, don't fake it (but document the possible empty response).
$newsItems[0]['image_url'] = $newsItems[0]['image_url'] ?? '/img/cat_placeholder.jpg';
php.net/manual/en/… \$\endgroup\$