I feel like I write this a lot in PHP:
$val = isset($var['foo']) ? $var['foo'] : '';
Is there a shorter way to write this? I can't use the ternary operator because the conditional is an isset
check, not the value of the function itself.
You could wrap it in a function (check the syntax, I don't actually know PHP):
function getDefault($array, $key, $default) {
return isset($array[$key]) ? $array[$key] : $default;
}
function getDefault(array $array, $key, $default)
.
\$\endgroup\$
Now three years later we have the Null Coalesce Operator in PHP7:
$val = $var['foo'] ?? '';
Building off of what Benjamin Kloster has
If you pass the parameter by reference instead of value it will not choke trying to pass in an invalid index.
function getDefault(&$isset, $default) {
return isset($isset) ? $isset : $default;
}
Or if you want a dynamic amount of parameters to default to
Just don't pass in any unknown indexes for them because I'm not sure how to do dynamic parameters as reference if that's even possible
ie: getDefault("default", $notSet, $stillNotSet, "isSet");
function getDefault($default, &$isset)
{
$argCount = func_num_args();
if ($argCount < 3)
return isset($isset) ? $isset : $default;
else
{
for($i = 0; $i < $argCount; $i++)
{
$arg = func_get_arg($i);
if (isset($arg))
return $arg;
}
return $default;
}
}
Another approach is
$foo = ''; // default value
extract($var); // extracts all array items to corresponding variables
This is not appropriate in all cases, eg. when:
But in other cases it's quite neat and clean.
If you want something fancier that supports nested structures, like such:
$foo = json_decode('{"bar":[42]}');
echo getDefault( $foo, '-default-', 'bar', 0 );
# 42
echo getDefault( $foo, '-default-', 'bar', 1 );
# -default-
echo getDefault( $foo, '-default-', 'missing' );
# -default-
... consider:
function getDefault( $container, $default /*, key1, key2 */ ) {
// get all remaining arguments
$keys = array_slice( func_get_args(), 2 );
while( $keys ) {
$key = array_shift( $keys );
if( is_array( $container ) && isset( $container[ $key ] ) ) {
$container = $container[ $key ];
} else if( is_object( $container ) && isset( $container->$key ) ) {
$container = $container->$key;
} else {
return $default;
}
}
return $container;
}
filter_var()
but that isn't any shorter really. Never got around to doing speed test on it. Benjamin's answer is your best bet. \$\endgroup\$$val = @$var['foo'];
. You may look at my previous answer at a similar question for detailed explanation. \$\endgroup\$