whats the difference in parentheses in IF statements? - php

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.

Related

PHP: Evaluate string as logical expression and return true or false

I have a txt file with hundreds of logical expressions.
I want to read each one (no problem so far) and to be able to evaluate it recursively, but I can't figure a way how. The expression has && and == and comparissons between strings and numbers. I don't want to use eval, as it's not recommended apparently and it didn't work in my case.
Example. Let's say I read these 2 strings:
s = "a == alpha && b == beta || b == omega", or
s = "g >= 2 && f != gamma"
I want to break them down to
($a == "alpha" && $b == "beta" || b == "omega")
($g >= 2 && f!= "gamma")
to use them in an if, so that it returns TRUE or FALSE. My problem is not with replacing the variables, it's with making them evaluate as a logical expression
Can anybody give me a hand?
Thanks in advance,
Cristina
Try this :
if( (($a == 'alpha' && $b == 'beta') || ($b == 'omega')) || ($g >= 2 && $f != 'gamma'))
{
// returns true
}
else
{
// returns false
}

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

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.

What is the difference between the OR and || operator in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Logical Operators, || or OR?
I've always thought that OR is another way of writing the || operator in PHP. The only way I prefer using OR over || is that it makes the code easier to read since || can be confused with II or 11 or whatever...
One day I stumbled upon this thing though:
<?php
$a = 'string_b';
$active = ($a == 'string_a') OR
($a == 'string_b') OR
($a == 'string_c');
var_dump($active); // Prints FALSE;
?>
Why is this happening?
The only difference is operator priority, see Operator precedence. || has a higher priority than OR.
By the way, var_dump($a) returns null but prints the right thing, string_b.
But, var_dump($active) will indeed produce an unexpected result, false.
In fact, = has higher priority than or, so your code is equivalent to:
($active = ($a == 'string_a')) OR ($a == 'string_b') OR ($a == 'string_c');
It first assigns false to active, then execute the right part of the first OR.
It's the same. But || has higher precedence than OR
http://php.net/manual/en/language.operators.precedence.php
= has a higher precedence than OR. So, $active = ($a == 'string_a') is evaluated first, which is false. Enclose the entire right hand side in it's own set of brackets and you'll get the result you were expecting.
<?php
$a = 'string_b';
$active = (
($a == 'string_a') OR
($a == 'string_b') OR
($a == 'string_c')
);
var_dump($active); // Prints TRUE;
?>

OR in PHP IF Statement

I am having trouble with my IF statement, it is always TRUE although this is incorrect. I'm using an OR operator as there are two possible scenarios I want to capture in the IF statement.
The array string ad_status is "1" but using the below -3 is returned, I'm expecting the IF to be FALSE. If I remove the OR and second statement from the IF, the result of the IF is correct.
What have I done wrong? Thanks.
if(($getadstatus['ad_status'] != "1" || $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
Additional:
What I want to do is exit the function (not seen in full here) if ad_status does not equal 1 or 4. If it equals any other value other than 1 or 4, the IF statement should return TRUE and exit.
ad_status could be any value from 0 to 4.
What you are saying is that any value that is not 1 OR is not 4 should return true.
For '1' you get the statement
if( 1 != 1 || 1 != 4)
which translates to
if( false || true )
which is ofcourse true.
What you need is:
if(!($value == 1 || $value==4))
which is the same as (de Morgan's law)
if($value != 1 && $value != 4)
You check:
ad_status != 1 -> FALSE
ad_status != 4 -> TRUE
if (FALSE OR TRUE) is always TRUE.
To be what you expected, replace OR with AND:
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
It will always be true as any value can't be both '1' and '4' at the same time.
You should use && operator because use !=. If you want to use || you could write like this:
if (!($getadstatus['ad_status'] == "1" || $getadstatus['ad_status'] == "4"))
You want to use &&
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
I personally prefer in_array instead of OR in IF statemements. Eg:
$array = array(1,4);
if (!in_array($getadstatus['ad_status'], $array)) {
// do whatever
}
There are no errors there.
If ad_status == 1 then your second condition will get you into the If
$getadstatus['ad_status'] != "4"
is true therefore you will get return -3;
If i got what you want you should use AND
if ( $a!= 1 AND $a!= 4 )
humm, ok I think I see. I'm attempting to be too clever. I want to use a single IF statement to check for two non related conditions. If ad_status does not equal 1 OR 4, return -3 and exit the function.
Okay, no problem, that can be expressed, just formulate like you write:
$status = $getadstatus['ad_status']; // assign a variable as it makes things easier to read.
if ( !( $status==1 || $status==4 ) )
{
return -3;
}
So the ! (not) should be on the whole OR comparison as you wrote in your sentence. That's probably in code what you had originally in mind. But as the order is important, the other part of your condition needs to be inside brackets to be calculated first, before using the not (!) operator.
Added:
The more sub-conditions are part of a condition or expression, the more complex it gets. But the more often you formulate complex conditions the better you will get with them. To train, you can always split conditions over multiple lines and assign labels (variables) to their part:
$status = $getadstatus['ad_status'];
$statusIs1or4 = $status==1 || $status==4;
$statusIsNot1or4 = !$statusIs1or4;
if ($statusIsNot1or4) return -3;
For production code this might be overuse, but as it's always the authors choice how to write something, you can do whatever the language allows.

PHP if or statement not working

We are trying to use the below piece of code
if (($_GET['1'] != "1") || ($_GET['1'] != "2")) {
When we try this no matter what value the variable has it will evaluate as true even when data is entered that is false. When we use
if (($_GET['1'] == "1") || ($_GET['1'] == "2")) {
and put in data that will make it return false it works correctly. We have reversed the way that the if statement goes just so we can get this working but i would like to know why this doesnt work, if it is something im doing wrong or a limitation within php with the or and the not equal operators
Thanks
Your first test is saying this:
If $_GET['1'] is anything other than "1" OR $_GET['1'] is anything other than "2"
The expression will always pass: If it equals 1 it will pass the != '2' test on the second half of your if statement. If it equals 2 it will pass the != '1' test on the first half, and never make it to the second half of the test.
The second test simply says:
If $_GET['1'] equals "1" OR $_GET['1'] equals "2" then the expression should pass
You probably want this expression, which will pass only if neither parameter holds the correct value:
if(($_GET['1'] != '1') && ($_GET['1'] != '2'))
The expression below will always evaluate to TRUE, because either x is not 1 or x is not 2. There is no way that x can equal both 1 and 2 at the same time!
($x != 1) || ($x != 2)
The opposite of
($x == 1) || ($x == 2)
is
($x != 1) && ($x != 2)
Note that you have to change the || to a &&.
Try:
if (($_GET['1'] != "1") && ($_GET['2'] != "2")) {
If you use != in both statements, then you need to use && instead of || to make sure both statements get evaluated.
Essentially, using || means that the first statement gets evaluated and if it is false, then PHP will ignore the second statement because you are using OR. But if you use &&, then PHP will be sure to evaluate both != statements.
if your code is:
if (($_GET['1'] != "1") || ($_GET['2'] != "2")) {
any value or even null value can enter this condition. you can change || to && meaning any string which is not equal to "1" and "2" can enter you condition
Without knowing the intention of the statement, or what input you started with (or how you revised it), I can't say for certain what the issue is.
That said, the first statement will only evaluate to FALSE if $_GET['1'] is equal to 1 and $_GET['2'] is equal to 2.
The second statement will only evaluate to FALSE if $_GET['1'] is not equal to 1 and $_GET['2'] is not equal to 2.
I'm guessing what you wanted on your first statement was
if (($_GET['1'] != "1") && ($_GET['2'] != "2")) {
which evaluates to FALSE unless $_GET['1'] is equal to 1 and $_GET['2'] is equal to 2.

Categories