PHP return if isset [duplicate]
Asked Answered
S

2

4

Possible Duplicate:
Any more concise way to set default values?

Is there a built-in php function like the following:

function isset_get($array, $key, $default = null) {
    return isset($array[$key]) ? $array[$key] : $default;
}

I don't like

$my_var = isset($my_array['some Key']) ? $my_array['some Key'] : '';

and would prefer

$my_var = isset_get($my_array, 'some Key', '');

or something similar...

Semple answered 29/12, 2012 at 23:46 Comment(3)
@Semple you've just made one, use it.Myocardium
:) Do you see an advantage in the later style?Semple
@Semple not really... but for similar (not exactly the same) functionality you could use $my_var = $my_array['key'] || $default;Ortrud
V
4

No. In my codebase we have several helpers of this nature. The names are pretty terrible but since they are frequently used, concision is warranted

idx($array, $key, $default) returns the $default if !isset($array[$key])

adx($array, $key, $default) like idx, but enforces that $array is actually an array and throws if not.

edx($array, $key, $default) returns the $default if !isset($array[$key]) or empty($array[$key])

Vilayet answered 29/12, 2012 at 23:57 Comment(0)
F
2

Consider using array_merge. Merging will overwrite keys of each given array allowing you to override an array of default values with the given values.

$defaults = array('some Key' => 'some Default Value');
$input = array('some Key' => 'a new value');
$merged = array_merge($defaults, $input);
$value = $merged['some Key'];

This won't work correctly for numeric keys however, so you should ensure you're working with an map instead of a vector.

Flaherty answered 29/12, 2012 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.