Search code examples
javascriptphpshortshorthand

PHP: do this || that (like javascript)


In javascript we can use || to perform a second action if the first one fails, like:

function getObject(id_or_object) {
    var obj = document.getElementById(id_or_object) || id_or_object;
    return obj;
}

How can we do this in PHP?

If we can't, I can swear I have seen this || used like this in PHP. What does it mean?

I want to do:

function fix_item($item) {
    $item['armor'] = $item['armor'] || 0;
    return $item;
}

But this doesn't work, so I'm using

function fix_item($item) {
    if (!isset($item['armor'])) $item['armor'] = 0;
    return $item;
}

, but I don't like the second method.. Any ideas?


Solution

  • You can use || (OR) for true/false comparison, but (this is one of the known (arguable) design errors) in PHP's design: short-circuit doesn't return the operand's value (as you were doing in your javascript-logic example) but the boolean result.

    That means that:
    $item['armor'] = $item['armor'] || 0; does not work as you intended (like it would in javascript).
    Instead, it would set $item['armor'] to boolean true/false (depending on the outcome of: $item['armor'] || 0 ).

    However, one can use the 'lazy evaluation' in a similar manner as you can use it in javascript:
    isset($item['armor']) || $item['armor'] = 0;
    (with an added isset to prevent an Undefined variable error).
    It still clearly describes what your intention is and you don't need to invert the boolean isset result using ! (which would be nececary for if and && (AND)).

    Alternatively, one can also do:
    $item['armor'] = $item['armor'] OR $item['armor'] = 0; (note that this will give an E_NOTICE)
    (I think readability is not so good),

    or ternary:
    $item['armor'] = isset($item['armor']) ? $item['armor'] : 0;
    (with 'better'/'more common' readabilty, but added code-size).

    For PHP7 and up, see Tom DDD 's answer.