Difference between "true == isset($variable)" and "isset($variable) == true" in php - 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

Related

Can you conditionally negate a function in PHP?

For example
$x = true;
return (($x ? "!" : "" ). is_null(NULL));
This obviously doesn't work, is there a way to do it?
The goal is to refactor this
$var == true
? array_filter($labels, function($v){return str_contains($v, 'return');})
: array_filter($labels, function($v){return !str_contains($v, 'return');});
Thanks
A common way of describing boolean combinations is as a truth table listing the possible inputs and outputs. In this case:
$x
is_null($var)
Desired result
false
false
false
false
true
true
true
false
true
true
true
false
So, the result you want is "either $x is true, or is_null($var) is true, but not both".
Looking in the PHP manual under "logical operators", we see that that's the definition of the xor operator, so you could write this:
return $x xor is_null($var);
An intermediate variable and simple if statement as shown in Justinas's answer is probably a lot more readable, though. Readability is extremely important in programming, because code is read far more times than it's written.
You can, but with different approach: first execute function and then check if it needs to be inverted
$result = is_null($var);
if ($x) {
// invert result from e.g. true to false
$result = !$result;
}
is_null returns a boolean. $x is a boolean. Compare both booleans:
return is_null($var) != $x;

PHP - What is the difference between '!== false' and ' == true'?

Sometimes I see people write conditional statements like this:
if($var !== false) {...}
Instead of like this:
if($var == true) {...}
These are the same, right?
I see the former used much more frequently and am wondering if there is a reason behind this, or if it is just personal preference.
I appreciate that this might be opinion based, but I am curious to see if there is a legitimate reason behind this.
This:
if($var !== false) {...}
will only evaluate to false if $var is exactly false. It will not evaluate to false if $var is any other value, whether 'false-y' or not.
This:
if($var == true) {...}
will evaluate to false for any 'false-y' value. e.g. 0, '0'.
In addition this:
if($var === true) {...}
will evaluate to true only if $var is exactly set to true, not other 'truthy-y' values.
So you are correct that they are the same if you know $var is exclusively one of either true or false, but they behave differently for other values.
$var !== false could be used for something other than readability or personal preference. Various PHP functions are expected to return false in case of error and they might as well return a falsy value on success. Take strpos for example:
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
This means the function can return an integer, even 0 if the needle was found at the beginning, and false if needle was not found. You have to use !== false to check if the expression is false, not falsy.
They're not the same.
!== is a strict comparison that compares value and type. $var has to equal (bool) false. This means if a string of 'false' was returned it would fail.
== is a loose comparison that just checks the value. This means $var can equal '(string) string' and be true. When checking a var like this:
if ($var == true) {
}
you check if $var has anything in it/defined. As long as something is a against it (and doesn't equal (bool) false) it will pass the conditional. This means '(string) false' would pass that conditional.
Worth nothing some functions (like strpos) return (bool) false so doing the first one (IMO) is better for those sort of functions.
When you use ==
First, it typecast the variable and compare are those values same.
You can see in the following example
var_dump(0==FALSE); // ( 0 == ( int ) false ) bool(true)
var_dump(0=='anystring'); // ( 0 == ( int ) 'anystring' ) bool(true)
When you use ===
It compares the value and types too
So it would be something like
var_dump( gettype( 0 ) == gettype( false ) && 0 == false )
This is faster in case if your type check fails Since it has not to typecast the value for further 'value check' if type check fails.

difference between $a==5 and 5==$a in 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

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

'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