Can't understand validation logic: === vs == - php

I'm learning validation stuff, and I just can't understand this:
if (strpos($value, "#") === false) { echo "Validation failed." }
What's the difference between === and ==? and why can't we use == instead and also why is it === false? does false means that # is not in the $value or it means 0 ?

The Equality Operator ==
A == B checks whether A and B are equal to each other, but not whether they are the same data type.
A pertinent example: 0 == false is true
The Identity Operator ===
A === B checks whether A and B are equal to each other also the same data type.
A pertinent example: 0 === false is false
Application Here
Applying this to your case, if the # was found as the first character of the string, strpos($value,"#") would return 0. If it is not found at all, it would return false.
So to avoid confusing these two situations, the test must use === rather than ==.
Useful references:
http://php.net/manual/en/function.strpos.php
http://php.net/manual/en/language.operators.comparison.php
I've assumed this is php, but the equality and identity operators are common to many programming languages.

Related

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.

evaluate stripos(), what is the difference between !== FALSE and === TRUE?

I have this issue with a string:
$val = 'NOT NULL';
if(stripos($val, 'NULL') !== FALSE){
echo "IS $val";
}
It evaluates fine, but if I use === TRUE as evaluator, things go wrong.
The answer eludes me, please help me understand.
If you read the documentation for stripos() you'll find.
Returns the position of where the needle exists relative to the beginnning 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.
It does not return TRUE. Since you are using strict equality, your condition will never be true.
If you did stripos($val, 'NULL') == TRUE then your code would execute if NULL were found at position 0 - since PHP will do some type-juggling and effectively 0 == (int)true.
The appropriate way to test for existence using stripos() is what you have:
if (stripos($val, 'NULL') !== FALSE){
echo "IS $val";
}
The answer is because you are using the strict equality operator. The function itself returns an int (or boolean if the needle is not found). The return value is not equal (in the strict sense, both value and type) to true, which is why the check fails.
Since === and !== are strict comparison operators - !== false is not the same as ===true since, for example, 1!==false is ok (values and types are not equal), but 1===true is not ok (values are equal, but types are not).
This sample indicates the meaning of strict comparison - i.e. not only values matters, but also types of compared data.

Coding method, why !== false

Why do I see people doing if (false !== $var) { instead of if (false === true) {
This answer consists of three parts:
The difference in order between (false == $var) and ($var == false)
The difference between == and ===
Why you see people doing (false !== $var) instead of if (false === true)
1. The difference in order between (false == $var) and ($var == false)
Because an often-made mistake is forgetting to put two = which results in an accidental attribution instead of comparison, some programmers decide to always put the invariable part of the equation on the left-side. This way, the accidental assignment is impossible and you don't risk getting
if ($var = false)
which assigns false to the variable $var and will always evaluate false instead of the desired
if ($var == false)
2. The difference between == and ===
The === or !== compares the variable's type as well as its value, whereas == and != compare value and convert types where needed.
Example:
0 == false // true
1 == true // true
0 === false // false
1 === true // false
0 !== false // true
0 !== true // true
false === false // true
false === true // false
$var !== FALSE is used because a lot of built-in PHP functions return FALSE on error, and a value on success. The value returned may be the same value as TRUE but it may not be the same type.
3. Why you see people doing (false !== $var) instead of if (false === true)
Your question itself made people snicker (that's why OrangeDog's comment was upvoted that much): if people did if (false === true), it would equal if(false) and would never execute the enclosing block. It still happens though, for example in JavaScript when part of the code is generated in a serverside-language, like PHP.
because its something completely different.
the first code part opens an if clause only if var is not false. it may be zero, null or an empty string. but not of type boolean and false.
the second one is a contradiction that can never ever happen.
Why do I see people doing if (false !== $var) {
Logic comparisons are a common foil for beginning programmers, and it is typical to see
$var = false
when what was meant
$var == false
So standard practice is to encourage programmers to always place variables on the right hand side, since $var=true is technically legal, but produces unexpected behavior, while true=$var is not legal and throws an error.
In your case it looks like ugly, if sensible, programming habits were taken to their logical end.

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

Is there a difference between !== and != in PHP?

Is there a difference between !== and != in PHP?
The != operator compares value, while the !== operator compares type as well.
That means this:
var_dump(5!="5"); // bool(false)
var_dump(5!=="5"); // bool(true), because "5" and 5 are of different types
!= is the inverse of the == operator, which checks equality across types
!== is the inverse of the === operator, which checks equality only for things of the same type.
!= is for "not equal", while !== is for "not identical". For example:
'1' != 1 # evaluates to false, because '1' equals 1
'1' !== 1 # evaluates to true, because '1' is of a different type than 1
!== checks type as well as value, != only checks value
$num = 5
if ($num == "5") // true, since both contain 5
if ($num === "5") // false, since "5" is not the same type as 5, (string vs int)
=== is called the Identity Operator. And is discussed in length in other question's responses.
Others' responses here are also correct.
Operator != returns true, if its two operands have different values.
Operator !== returns true, if its two operands have different values or they are of different types.
cheers
See the PHP type comparison tables on what values are equal (==) and what identical (===).

Categories