difference between $a==5 and 5==$a in php - php

Today I have faced a question, I was unable to answer it,
I have tried by making a php program but was unable to find out the exact reason for it
if $a=5 then both($a==5 and 5==$a) are giving me output as boolean true and,
if $a != 5 then both ($a==5 and 5==$a ) are giving me output as boolean false
Can anyone tell me what is the difference between $a==5 and 5==$a from any language point of view.
**Program**
$a = 3;
var_dump( 5==$a );
var_dump( $a==5 );
$a = 5;
var_dump( 5==$a );
var_dump( $a==5 );
**Output**
boolean false
boolean false
boolean true
boolean true

Comparisons like that are not affected by which value you write first. However, it is best practice to put the literal first, e.g. 5 == $x because if you mess up and only enter one equals sign, you'll get an error instead of an accidental value assignment, which is far easier to debug.

No difference
but 5 == $a prevents some error if you forgot one '='.
For example $a = 1
if you write if ($a = 5) - $a value becomes 5
if you write if (5 = $a) - you got error

It's just a technique, that prevents you from accidentally using assignment instead of comparison. The if operator happily accepts $a = 5, while 5 = $a throws an error, preventing you from creating a nasty bug.

5 == $a is logically the same as $a == 5
This format, commonly referred to as yoda conditions and does not affect the logical comparison.
https://en.wikipedia.org/wiki/Yoda_conditions
It is preferred, commonly in PHP, to prevent accidental assignment in conditions, which will always evaluate as either truthy or falsy, but will not actually perform the indented condition check:
if ($a = 5) {
// always run... oops
} else {
// never run
}
The WordPress PHP Coding Standards have a good explanation of this as well

Related

how ordering makes a difference within an expression for an if statement

I have an array ...
$a= array(1,2,3,4);
if (expr)
{ echo "if";
}
else
{ echo 'else';
}
When expr is ( $a = '' || $a == 'false') , output is "if" ,
but when expr is ( $a == 'false' || $a = '' ) , output is "else"
Can anyone explain why & how ordering makes a difference ??
Edit : I understand that I am assigning '' to $a. That is not the problem. The real question is : What does the expression $a = '' return? And why does reversing the order of the 2 situations switch us from the IF section to the ELSE section?
AGAIN : I UNDERSTAND I AM ASSIGNING NOT COMPARING. PLEASE ANSWER THE QUESTION AS IS.
First, never use = as a comparison operator. It is an assignment operator.
The difference is that false (as a boolean) is not the same as 'false' as a string.
Certain expressions are type juggled by PHP to evaluate somewhat differently to how you would expect.
false==""
// TRUE.
false=="false"
// FALSE.
Additionally, when you try to compare numbers to strings, PHP will try to juggle the data so that a comparison will be performed. There is a lot to it (much more than I will post here) but you would do well to investigate type juggling and various operators. The docs are a great start for this. You should also have a read of the comparison operators which go into a lot of detail about how various comparisons will work (depending on whether you use == or === for example).
With $a = '' you are setting $a to an empty string. This is the same as:
$a = '';
if($a){
echo 'if';
}
The || operator checks if the first condition is true and if it is, it continues with the code in the brackets. In PHP, if $a is set to anything, it will return true. In the second case $a does not equal the string 'false' (you are not comparing it to a boolean false even!), so it executes the code in the else part.
And Fluffeh is not entirely correct. You can use the assignment operator in an if condition very effectively, you just have to be smart about it.
$a = '' is an assignment: you have, in error, used = in place of ==. Assignment is an expression which has the value of the thing your assigning.
A single equals sign = is the assignment opporator, so $a = '' is assigning an empty string to $a not checking if it is equal to.
In your 1st example you set the value of $a to an empty string, then check if it is false. An empty tring evalutes to false in php, so the conditional is true.
In your second example, you check if $a equals false 1st (when the value of $a is an array), so the conditional is false

Difference between "true == isset($variable)" and "isset($variable) == true" in php

I was just wandering the about the concept of equating the condition in PHP that is,
what could be the difference between
true == isset($variable)
and
isset($variable) == true
?
For this specific case, no difference.
The first syntax is used to prevent accidental assignment instead of comparison.
if ( true = $x ) // would yiled error
if ( $x = true ) // would work
But again, in your case, no difference.
Elaboration:
Say you want to compare a variable $x to true and do something. You could accidentally write
if ( $x = true )
instead of
if ( $x == true )
and the condition would always pass.
But if you get into the habit of writing
if ( true == $x )
these mistakes wouldn't happen, since a syntax error would be generated and you would know in advance.
There is no difference. But isset() itself returns a boolean value.
So never use
if (true == isset($variable))
Just:
if (isset($variable))
Remember that when php parses that true is actually defined and its equal to 1. Furthermore so is false and it is equal to 0. php automatically checks these for comparison with these values in an IF statement. You'll be safe using the ! operator, because its the same as if ($something == false) good luck!
Would it be Java, there was difference.
i.e.
String test = null;
if("".equals(test)){
System.out.println("I m fine..");
}
if(test.equals("")){
System.out.println("I m not fine..");
}
There is no "real" diffrences(in this case)
Between
true == isset($variable) AND
isset($variable) == true

Short-circuit evaluation via the AND operator in PHP

I'm trying to improve my coding ninja h4x skills, and I'm currently looking at different frameworks, and I have found sample code that's pretty hard to google.
I am looking at the FUEL framework used in a project.
The sample I don't understand is
$data and $this->template->set_global($data);
What is the and keyword doing in this line of code? It is used many places in the framework and it's the first that I have found that uses it.
This is a type of "short circuit evaluation". The and/&& implies that both sides of the comparison must evaluate to TRUE.
The item on the left of the and/&& is evaluated to TRUE/FALSE and if TRUE, the item on the right is executed and evaluated. If the left item is FALSE, execution halts and the right side isn't evaluated.
$data = FALSE;
// $this->template->set_global($data) doesn't get evaluated!
$data and $this->template->set_global($data);
$data = TRUE;
// $this->template->set_global($data) gets evaluated
$data and $this->template->set_global($data);
Note these don't have to be actual boolean TRUE/FALSE, but can also be truthy/falsy values according to PHP's evaluation rules. See the PHP boolean docs for more info on evaluation rules.
When you use logical operators, operands (the value on the left and the value on the right) are evaluated as boolean, so basically that code will do this, in a shorter way:
$o1 = (Bool)$data; // cast to bool
if($o1)
$o2 = (Bool)$this->template->set_global($data); // cast to bool
Edit:
Some additional information:
$a = 33;
isset($a) && print($a) || print("not set");
echo "<br>";
isset($a) AND print($a) OR print("not set");
echo "<br>";
Try to comment/decomment $a = 33;. This is the difference between && and AND, and between || and OR (print returns true that is casted to "1" when converted to string).
It is a valid statement and works like this:
If $data is valid (is not '', 0 or NULL) then run $this->template->set_global($data)
It's a quick way of saying:
if ($data)
{
$this->template->set_global($data);
}
Btw you can also use && instead of and
PHP supports both && and and for the logical AND operation, and they generally work identically, except and has a slightly lower operator precedence than &&: http://php.net/manual/en/language.operators.precedence.php
It's a boolean operator which means it takes two operands and returns a boolean value-- true or false. If both operands evaluate to true (anything but and empty string, zero or null in PHP) it will return true, otherwise the result will be false.
Here's PHP's official docs on the and operator: http://www.php.net/manual/en/language.operators.logical.php
<?php
$a = true and false; # FALSE
$b = true and 5; # TRUE
$c = '' and 0; # FALSE
$d = null and true; # FALSE
?>

The strange ways of the "or" in PHP

PHP's or is an weird keyword. Here it is in a code snippet that makes me confused:
echo 0 or 1; // prints 1
$foo = (0 or 1);
echo $foo; // prints 1
$foo = 0 or 1;
echo $foo; // prints 0 for some reason
Why does the last one print 0 and not 1?
This is because of different operator precedence. In the third case, the assignment is handled first. It will be interpreted like this:
($foo = 0) or 1;
The || operator has a different precedence. If you use
$foo = 0 ||1;
It will work as you expect.
See the manual on logical operators
No, I wouldn't, that's because of operator precedence:
$foo = 0 or 1;
// is same as
($foo = 0) or 1;
// because or has lower precedence than =
$foo = 0 || 1;
// is same as
$foo = (0 || 1);
// because || has higher precedence than =
// where is this useful? here:
$result = mysql_query() or die(mysql_error());
// displays error on failed mysql_query.
// I don't like it, but it's okay for debugging whilst development.
It's ($foo = 0) or 1;. or has a lower operator precedence than = .
You should use || in this case, since it has a higher precedence than =, and thus will evaluate as you'd expect.
IIRC, the assignment operator (=) has higher precedence than or. Thus, the last line would be interpreted as:
($foo = 0) or 1;
Which is a statement that assigns 0 to $foo, but returns 1. The fist statement is interpreted as:
echo(0 or 1);
An as such will print 1.
Order of operations. The word "or" has much lower precedence than the corresponding "||". Lower, even, than the assignment operator. So the assignment happens first, and the value of the assignment is the first operand to the "or".
"or" is meant more to be used for flow control than for logical operations. It lets you say something like
$x = get_something() or die("Couldn't do it!");
if get_something is coded to return false or 0 on failure.
In the first two snippets, you are comparing 0 or 1 (essentially true or false). In the third snippet you are assigning 0, which works, and thus is true, so therefore the or condition is not executed.emphasized text
In your third example, the = operator has a higher precedence than or, and thus gets done first. The || operator, superficially the same, has a higher precedence than =. As you say, interesting.

'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.

Categories