phpshorthand-if

PHP If Shorthand Best Practce


Just a weird PHP question about best practice. Assuming the following function:

function get_option($val) {
  return false;
}

I want to assign to a $locale variable, the value returned from this function and, if false, set to a default en_GB one. I discovered 2 option for achieving this goal:

1st Option:
$locale = ( $locale = get_option( 'language_code' ) ) ? $locale : 'en_GB';

2nd Option:
$locale = get_option( 'language_code' ) ? get_option( 'language_code' ) : 'en_GB';

I would like to know which one is more correct and why.

Thanks


Solution

  • Both seem a bit verbose to me, to avoid duplicated calculations, I would prefer the first one (perhaps splitted to 2 lines of code).

    You can create a helper function, this one has false hardcoded, but you could even pass it as a parameter:

    function use_default_false($var, $default) {
        return ($var !== false) ? $var : $default;
    }
    

    Then your code becomes:

    $locale = use_default_false(get_option('language_code'), 'GB');
    

    Since PHP5.3 you can use the shorthand ternary operator ?:.

    Be aware that it will check the left-hand side argument for truthy, which prevents it to be used if the valid value you're checking evaluates to false (e.g.: 0, "", "0", array()...). Because of that, I wouldn't generally recommend it, but in this case I assume the locale is a non-empty non-"0" string, so it should be fine.

    $locale = get_option('language_code') ?: 'GB';
    

    With PHP7 you can use the null coalesce operator ??.

    It checks for NULL so you have to alter the default value returned by your function.

    $locale = get_option('language_code') ?? 'GB';