1

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?

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

if you are using php 7 you can use the null coalesce operator

$a ?? $b ?? $c 

this evaluates to the first non null value. Which is very simmilar to the || from javascript.

1 Comment

PHP 7 isn't generally available yet.
1

This tests $item['armor'], if it is true it returns what is to the right of the ? operator, if it is false it returns what is immediately to the right of : (I've used the ternary operator in javascript, too).

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

3 Comments

You've missed : somewhere.
You're totally right!function fix_item($item) { $item['armor'] = $item['armor'] ? $item['armor'] : 0; return $item; }
So why not fix the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.