Difference Between (x && y || z) and (x AND y OR z) - php

I was wondering if there are any disadvantages of using words (e.g. AND, OR) instead of their code equivalents (&&, ||) for comparison? Besides the later being a compatible syntax with many other programming languages, is there any other reason for choosing them?

AND is not the same like &&
for example:
<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>
the first thing is
(a and b) or c
the second
a and (b or c)
because || has got a higher priority than and, but less than &&
For more information check out PHP Logical Operators and Operator Precedence

An unanticipated disadvantage comes when used with the = operator.
$result = false || true; # true, $result is true
/* Translated to result = (false || true) */
and
$result = false or true; # true, $result is false
/* Translated to (result = false) or true */

The PHP manual (in Logical Operators) talks about what you ask in your question:
The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)
So the difference is in the precedence, not the logical meaning of each single operator.
In your example: (x && y || z) and (x AND y OR z) you won't see any difference between the two expressions.

They do the same thing, but the && and || operators have higher precedence than AND and OR.
Basically I think this can become confusing so if you just stick to one notation and not mix them, you'll be fine and your code will remain readable.

Related

logical vs assignment operator precedence in PHP

Recently i came upon such snippet:
$x = 2 && $y = 3; echo (int)$x.':'.(int)$y;
Which produces output 1:3.
By looking at operator precedence sheet i see that logical operators || and && has higher precedence than assignment operator =. So first expression should be evaluated as $x = (2 && $y) = 3; which becomes $x = (2 && null) = 3; and finally evaluates to $x = false = 3; Secondly - assignment operator has right associativity, so interpreter should try to execute false = 3 which is illegal of course. So in my opinion above mentioned code snippet should not compile at all and must throw parse or run-time error. But instead of that script produces 1:3. Which means that interpreter executed actions are:
a) $y=3
b) 2 && $y
c) $x = (2 && $y)
Why it is so and not according to operator precedence ?
The operator precedence sheet you link to states as a separate note:
Although = has a lower precedence than most other operators, PHP will
still allow expressions similar to the following: if (!$a = foo()), in
which case the return value of foo() is put into $a.
So, in effect, an assignment inside an expression will be treated somewhat like a sub-expression. Exactly how and when this will happen isn't clear from the documentation, which just states that "similar" expressions will work this way.

PHP "or" syntax statement

Moving over to PHP from another language and still getting used to the syntax...
What's the proper way to write this statement? The manual on logical operators leaves something to be desired..
if($var !== '5283180' or '1234567')
Generally, comparison is by using == and the reverse is !=. But if you want to compare values along with its data type, then you can use === and the reverse is !==.
Please refer to the documentation for more information.
You can use the following:
if($var!='5283180' || $var!='1234567')
Try this
if($var != '5283180' || $var != '1234567')
PHP's or functions identically to the normal ||, but has a lower binding precedence. As such, these two statements:
$foo = ($bar != 'baz') or 'qux';
$foo = ($bar != 'baz') || 'qux';
might appear to be otherwise identical, but the order of execution is actually quite
different. For the or version, it's executed as:
($foo = ($bar != 'baz')) or 'qux';
- inequality test is performed
- result of the test is assigned to $foo
- result of the test is ORed with the string 'qux';
For the || version:
$foo = (($bar != 'baz') || 'qux');
- inquality test is performed
- result of test is ||'d with 'qux'
- result of the || is assigned to $foo.
To build on the others, as the OP mentioned they are new to PHP, there is a couple things to be considered.
First off, the PHP or that you're looking for is the double line (||) and each item must be a statement on each side of the ||.
if ( $var !== '5283180' || $var !== '1234567')
addition:
As mentioned in the PHP Manual
The or operator is the same as the || operator but takes a much lower precedence.
Such as the given example (from manual):
// The constant false is assigned to $f and then true is ignored
//Acts like: (($f = false) or true)
$f = false or true;
Now as mentioned, there is the general comparison (== or 'Equal') and the type comparison (=== or 'Identical'), with both having the reverse (not). In the given example, the test will check that $var is not identical to the values.
From PHP Manual:
$a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type.
With this said, double check that this is what you're actually trying to accomplish. Most likely you're looking for !=.

whats the difference in parentheses in IF statements?

I've noticed in my dealings with PHP & javascript, still learning btw, that the following seems to produce the same results.
if( ( $A==0 ) && ( $B==0 ) ){}
if( $A==0 && $B==0 ){}
What is the proper term for this in programming so I can learn more about it.
Parenthesis determine the order in which comparisons are made. Your example is a pretty simple one that doesn't need parenthesis at all, but look at something like this
if ($a == 0 || $b == 0 && $c == 0 || $dd == 0)
This is actually equivalent to
if ($a == 0 || ($b == 0 && $c == 0) || $dd == 0)
because && is evaluated first in PHP as it has a higher precedence than the ||
IN most cases, when you have complex conditionals, you want to make sure to use parenthesis, if not to get the order of operations right, then at least to make it clear to the code reader what you are trying to do.
The term is called operator precedence.
http://php.net/manual/en/language.operators.precedence.php
Due to Operator Precedence rules, the two lines are the same.
The == takes precedence over the && operator.
Extra (unnecessary) parentheses are sometimes used to make a statement clearer, or sometimes used because the author doesn't know the precedence, or due to voodoo programming
Order of operations, as #asawyer said.
Source: http://en.wikipedia.org/wiki/Order_of_operations#Programming_languages
IN your specific example there is no difference, however, there are cases when paranthethis makes a big difference.
Example:
if(a == 0 && (b == 0 || c == 0)) {
// do something
}
If you noticed, in this case only 2 out of 3 variables have to be 0 in o
What you are seeing is extra parentheses based on the Order of Operations. Parentheses are used to override the usual order. To take a mathematical example:
7 + 2 * 4 + 3
Will first have 2 * 4 evaluated to 8, giving:
7 + 8 + 3
Multiplication has a higher precedence than addition, so it is evaluated first. You can override that by using parentheses:
(7 + 2) * 4 + 3
In this case, the first operation to be evauluated is the addition, giving:
9 * 4 + 3
The same principle is in effect for bit-wise, boolean, and comparison operators in an if statement. Comparison operations have a higher precedence than boolean operators, so if you have, for example:
1 == 4 || 7 > 3
the comparisons will be evaluated first, giving
false || true
A lot of programmers are used to programming "safely", by putting parentheses around the comparisons:
(1 == 4) || (7 > 3)
In a way, this makes the code look a bit cleaner and guarantees that the comparison will be evaluated first.
It is called operator precedence
if( ( $A==0 ) && ( $B==0 ) ){}
if( $A==0 && $B==0 ){}
In your example both lines evaludate the same. Basically things in parenthesis get processed first.This can be noticed better when you have something like:
if( ( $A==0 && $C!= 1) && ( $B==0 || $D >0) ){}
In the above example. The conditions inside ( $A==0 && $C!= 1) and ( $B==0 || $D >0) are first evalulated, and then results are evaluated against the main && sign.
So supposing:
( $A==0 && $C!= 1) evaluated to TRUE
and
( $B==0 || $D >0) evaluated to FALSE
The condition
if( ( $A==0 && $C!= 1) && ( $B==0 || $D >0) ){}
becomes
if( ( TRUE) && ( FALSE) ){}
which naturally evaluates to FALSE in the end
the brackets are used when dealing with multiple && and || also known as and and or. It's a lot like math where if you have the equation 2+4*2=10 this is because you do the multiplication before the addition. where as (2+4)*2=12 because the brackets make you do the addition.
So in a nutshell brackets have the highest precedence in the if operation.
I hope that makes this clearer for you. have a nice day.
You should combine the two arguments if you want to check both conditions simulataneously, but by separating them by using two different parentheses sets you are checking each condition for each loop inside the if statement.

'AND' vs '&&' as operator

I have a codebase where developers decided to use AND and OR instead of && and ||.
I know that there is a difference in operators' precedence (&& goes before and), but with the given framework (PrestaShop to be precise) it is clearly not a reason.
Which version are you using? Is and more readable than &&? Or is there no difference?
If you use AND and OR, you'll eventually get tripped up by something like this:
$this_one = true;
$that = false;
$truthiness = $this_one and $that;
Want to guess what $truthiness equals?
If you said false... bzzzt, sorry, wrong!
$truthiness above has the value true. Why? = has a higher precedence than and. The addition of parentheses to show the implicit order makes this clearer:
($truthiness = $this_one) and $that
If you used && instead of and in the first code example, it would work as expected and be false.
As discussed in the comments below, this also works to get the correct value, as parentheses have higher precedence than =:
$truthiness = ($this_one and $that)
Depending on how it's being used, it might be necessary and even handy.
http://php.net/manual/en/language.operators.logical.php
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
But in most cases it seems like more of a developer taste thing, like every occurrence of this that I've seen in CodeIgniter framework like #Sarfraz has mentioned.
Since and has lower precedence than = you can use it in condition assignment:
if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false
For safety, I always parenthesise my comparisons and space them out. That way, I don't have to rely on operator precedence:
if(
((i==0) && (b==2))
||
((c==3) && !(f==5))
)
Precedence differs between && and and (&& has higher precedence than and), something that causes confusion when combined with a ternary operator. For instance,
$predA && $predB ? "foo" : "bar"
will return a string whereas
$predA and $predB ? "foo" : "bar"
will return a boolean.
Let me explain the difference between β€œand” - β€œ&&” - "&".
"&&" and "and" both are logical AND operations and they do the same thing, but the operator precedence is different.
The precedence (priority) of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.
Mixing them together in single operation, could give you unexpected results in some cases
I recommend always using &&, but that's your choice.
On the other hand "&" is a bitwise AND operation. It's used for the evaluation and manipulation of specific bits within the integer value.
Example if you do (14 & 7) the result would be 6.
7 = 0111
14 = 1110
------------
= 0110 == 6
which version are you using?
If the coding standards for the particular codebase I am writing code for specifies which operator should be used, I'll definitely use that. If not, and the code dictates which should be used (not often, can be easily worked around) then I'll use that. Otherwise, probably &&.
Is 'and' more readable than '&&'?
Is it more readable to you. The answer is yes and no depending on many factors including the code around the operator and indeed the person reading it!
|| there is ~ difference?
Yes. See logical operators for || and bitwise operators for ~.
Another nice example using if statements without = assignment operations.
if (true || true && false); // is the same as:
if (true || (true && false)); // TRUE
and
if (true || true AND false); // is the same as:
if ((true || true) && false); // FALSE
because AND has a lower precedence and thus || a higher precedence.
These are different in the cases of true, false, false and true, true, false.
See https://ideone.com/lsqovs for en elaborate example.
I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:
true && false || false; // returns false
true and false || false; // returns true
Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.
UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:
var_dump(true and false || false); // bool(false)
$a = true and false || false; var_dump($a); // bool(true)
The reason why $a === true is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.
Here's a little counter example:
$a = true;
$b = true;
$c = $a & $b;
var_dump(true === $c);
output:
bool(false)
I'd say this kind of typo is far more likely to cause insidious problems (in much the same way as = vs ==) and is far less likely to be noticed than adn/ro typos which will flag as syntax errors. I also find and/or is much easier to read. FWIW, most PHP frameworks that express a preference (most don't) specify and/or. I've also never run into a real, non-contrived case where it would have mattered.

What does "===" mean? [duplicate]

This question already has answers here:
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 4 months ago.
I've noticed someone using the PHP operator === which I can't make sense out of. I've tried it with a function, and it corresponds in crazy ways.
What is the definition of this operator? I can't even find it in the declaration of PHP operators.
$a === $b (Identical)
TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
PHP Docs
http://www.php.net/ternary
$a == $b Equal TRUE if $a is equal to $b, except for (True == -1) which is still True.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
> "5" == 5;
True
> "5" === 5;
False
You can read here, short summary:
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
In PHP you may compare two values using the == operator or === operator. The difference is this:
PHP is a dynamic, interpreted language that is not strict on data types. It means that the language itself will try to convert data types, whenever needed.
echo 4 + "2"; // output is 6
The output is integer value 6, because + is the numerical addition operator in PHP, so if you provide operands with other data types to it, PHP will first convert them to their appropriate type ("2" will be converted to 2) and then perform the operation.
If you use == as the comparison operator with two operands that might be in different data types, PHP will convert the second operand type, to the first's. So:
4 == "4" // true
PHP converts "4" to 4, and then compares the values. In this case, the result will be true.
If you use === as the comparison operator, PHP will not try to convert any data types. So if the operands' types are different, then they are NOT identical.
4 === "4" // false
$x == $y is TRUE if the value of the $x and $y are same:
$x = 1; //int type
$y = "1"; //string type
if ($x == $y) {
// This will execute
}
$x === $y TRUE if the value of the $x and $y are same and type of $x and $y are same:
$x = 1; //int type
$y = "1"; //string type
if ($x === $y) {
// This will not execute
}
You'll see this operator in many dynamically typed languages, not just PHP.
== will try to convert whatever it's dealing with into types that it can compare.
=== will strictly compare the type and value.
In any dynamically typed language you have to be careful with ==, you can get some interesting bugs.
The ternary === is less convenient, but it's safer. For comparisons you should always give some additional thought to whether it should be === or ==
The triple equals sign === checks to see
whether two variables are equal and of the same type.
For PHP, there many different meanings a zero can take
it can be a Boolean false
it could be a null value
It could really be a zero
So === is added to ensure the type and the value are the same.
See Double and Triple equals operator in PHP that I got for googling on "PHP three equals operator".
At one point it says that:
A double = sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
A triple = sign is a comparison to see whether two variables / expresions / constants are equal AND have the same type - i.e. both are strings or both are integers.
It also gives an example to explain it.
"===" matching the value in the variable as well as data type of the variable.

Categories