Alex
Alex

Reputation: 68004

PHP - and / or keywords

Is && the same as "and", and is || the same as "or" in PHP?

I've done a few tests, and it seems they behave the same. Are there any differences?

If not, are there any other PHP signs that have word equivalents and do you think it makes the code easier to read?

Upvotes: 22

Views: 12044

Answers (4)

Bruno Lima
Bruno Lima

Reputation: 321

The difference is on the precedence. But not only compared with each other!

In most cases you won't mind it, but there are specific cases when you have to take one step back and look at the big picture. Take this, for example:

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;

// The constant true is assigned to $h before the "and" operation occurs
// Acts like: (($h = true) and false)
$h = true and false;

var_dump($g, $h);

This will produce, respectively:

bool(false)
bool(true)

In other words, && has higher preference than =, which has higher precedence than and, as stated in http://php.net/manual/en/language.operators.precedence.php. (It is mentioned in other answers, but I think it's worth to detail, since a misuse can lead to logical errors)

I hope it may help you. You can find more at http://php.net/manual/en/language.operators.logical.php

Upvotes: 4

K G
K G

Reputation: 51

What bothers me is:

echo (false and false ? true : true);
// (empty/false)

You might guess there is only the possible output of "1" (true) as there is no case which could output a false... ...but it will be "" (false).

Using && as a operator in this case satifies at least my expectations:

echo (false && false ? true : true);
// 1

So, in some cases the usage matters significantly.

Upvotes: 5

John Parker
John Parker

Reputation: 54445

Yes, they are logically the same. (I believe "&&" and "||" are the preferred choice in the Zend coding standards, but I can't find any specific information on this, so it might all have been a dream. Or something.)

That said:

  1. "&&" and "||" are of a higher precedence than "AND" and "OR" (unlikely to ever be relevant, but you never know).

  2. A lot of other languages use "&&" and "||", rather than the textual equivalents so it might be an idea to go with this.

  3. As long as you use your choosen set of operators consistently it doesn't really matter.

Upvotes: 7

Mchl
Mchl

Reputation: 62387

and and or have higher lower precedence than && and ||. To be more exact && and || have higher precedence than assignment operator ( = ) while and and or have lower.

http://www.php.net/manual/en/language.operators.precedence.php

Usually it doesn't make a difference, but there are cases when not knowing about this difference can cause some unexpected behaviour. See examples here:

http://php.net/manual/en/language.operators.logical.php

Upvotes: 38

Related Questions