Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - and / or keywords

Tags:

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?

like image 541
Alex Avatar asked Dec 21 '10 17:12

Alex


People also ask

Is $this a keyword in PHP?

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.

Can you use keywords for variable names in PHP?

What is a keyword. In PHP there are certain words that's reserved for a special use. We cannot use these words when naming our variables, constants, arrays, functions, interfaces and classes. These keywords have special meaning and is only to be used in special contexts.


2 Answers

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

like image 59
Mchl Avatar answered Sep 21 '22 19:09

Mchl


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.

like image 41
John Parker Avatar answered Sep 24 '22 19:09

John Parker