Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
    
I toyed around with using 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. –  mseancole Jun 19 '12 at 13:42

4 Answers 4

up vote 6 down vote accepted

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;
}
share|improve this answer
2  
Was just about to post that! :) (And your syntax is correct, though I would probably do function getDefault(array $array, $key, $default). –  Corbin Jun 19 '12 at 6:11

Another approach is

$foo = ''; // default value
extract($var); // extracts all array items to corresponding variables

This is not appropriate in all cases, eg. when:

  • You don't want to extract all array elements, just one
  • You want to extract the variable to a different name (it's possible to specify a prefix though, so the item will extract to $prefix_foo)
  • You don't want to pollute your name space

But in other cases it's quite neat and clean.

share|improve this answer

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($notSet, $stillNotSet, "isSet");

function getDefault(&$isset, $default)
{
    $argCount = func_num_args();
    if ($argCount < 3)
        return isset($isset) ? $isset : $default;
    else
    {
        for($i = 1; $i < $argCount; $i++)
        {
            $arg = func_get_arg($i);
            if (isset($arg))
                return $arg;
        }
    }
}
share|improve this answer

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;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.