This question already has answers here:
The 3 different equals
(5 answers)
Closed 9 years ago.
Does it really matter to put variables after == or === when doing comparisons?
if (null == $var) {
}
if ($var == null) {
}
I've constantly seen coders prefer this way, is it for speed difference?
Updates:
Sorry I didn't make my question clear, what I want to know is not the different between == and ===, but expressions like null == $var and $var == null, so I've changed the code example.
Conslusion:
No functional or performance difference. Some consider it a best practice or simply a coding style. BTW it has a cool name: Yoda Conditions :)
FYI: PHP error messages use this style, e.g.
PHP Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
Don't know why this question is marked duplicated to (The 3 different equals) not (What's the difference between 'false === $var' and '$var === false'?)
It prevents typos which cause very hard to debug bugs. That's in case you accidentally write = instead of ==:
if ($var == null) # This is true in case $var actually is null
if ($var = null) # This will always be true, it will assign $var the value null
Instead, switching them is safer:
if (null == $var) # True if $var is null
if (null = $var) # This will raise compiler (or parser) error, and will stop execution.
Stopping execution on a specific line with this problem will make it very easy to debug. The other way around is quite harder, since you may find yourself entering if conditions, and losing variable's values, and you won't find it easily.
I think that the following code will explain it:
echo (( 0 == NULL ) ? "0 is null" : "0 is not null") ."\n";
echo (0 === NULL) ? "0 is null" : "0 is not null" ;
it will output:
0 is null
0 is not null
The === operator checks for both value and type, but 0 is a number while NULL is of type NULL
The == operator checks only for value and zero can be casted to "false" or "null" hence the "truthy" that we get for the first line
Compare results from this to ifs.
echo "Test '1abc' == 1 - ";
if ('1abc' == 1) {
echo 'ok';
} else {
echo 'fail';
}
echo "\nTest '1abc' === 1 - ";
if ('1abc' === 1) {
echo 'ok';
} else {
echo 'fail';
}
Then read this page http://php.net/manual/en/language.types.type-juggling.php it's very interesting lecture ;)
Related
This question already has answers here:
Is there a difference between !== and != in PHP?
(7 answers)
difference between != and !== [duplicate]
(4 answers)
The 3 different equals
(5 answers)
Closed 3 years ago.
I have two statements like this:
$ready = true;
if($ready === true) {
echo "it's ready!";
}
And this:
$ready = true;
if($ready !== false) {
echo "it's ready!";
}
I know those mean the same thing as === true and !== false is the same thing. I see people use the negation type (is not false or is not {something}). like this: https://stackoverflow.com/a/4366748/4357238
But what are the pros and cons of using one or the other? Are there any performance benefits? Any coding benefits? I would think it is confusing to use the negation type rather than the straight forward === true. Any input would be appreciated! thank you
These do not mean the same thing, and you can see this demonstrated below:
$ready = undefined;
if($ready === true) {
console.log("it's ready 1");
}
if($ready !== false) {
console.log("it's ready 2");
}
When in doubt, stick with ===. You're comparing to exactly what it should be. "This should exactly be equal to true" vs "This should be equal to anything but exactly false" are 2 separate statements, the second including a lot of values that would be true (As demonstrated above, undefined is not exactly false, so this would be true).
Most PHP functions return false as failure, such as strpos, from the manual it says:
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.
So it returns an integer or false, then it is wrong to use strpos() === true
strpos() !== false is the right way to check the result.
It is not about performance and they are not the same. It helps us in reducing unnecessary if else statements.
Consider this: there is a variable foobarbaz whose value can be anything among foo/ bar/ baz/ foobar/ barbaz. You need to execute a statement if the value is not foo. So instead of writing like this:
if(foobarbaz === "bar" || foobarbaz === "baz" || foobarbaz === "foobar" || foobarbaz === "barbaz") {
//some statement
}
else if(foobarbaz === "foo") {
//do nothing
}
You can write something like this:
if(foobarbaz !== "foo") {
//some statement
}
You can see we were able to eliminate the unnecessary else statement.
In php == compare only the values are equal. For and example
$ready = 'true';
if($ready == true) {
echo "true";
}
else{
echo "false";
}
It print true.But if it is compare with === it not only check the values but also it check the datatype. So it compares with === it print the false.
Talking about !== it's work as the same. So it's not a problem to output if you use
if($ready === true)
or
if($ready !== false)
Can't compare these two because both are same.
This question already has answers here:
php array_search returning 0 for the first element?
(4 answers)
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
(13 answers)
Closed 5 years ago.
Why does example A fail, but example B work?
A) FAIL:
$request_IP = '8.8.8.8';
$list_Array = explode(',', "8.8.8.8,9.9.9.9,2.2.2.2");
$result = array_search($request_IP, $list_Array);
if($result) {
// Expecting - to get it success there
}
else {
echo "FAIL";
exit;
}
B) WORKS:
$request_IP = '8.8.8.8';
$list_Array = explode(',', "0,8.8.8.8,9.9.9.9,2.2.2.2");
$result = array_search($request_IP, $list_Array);
if($result) {
// In this case it works??
}
else {
echo "FAIL";
exit;
}
From the documentation for array_search:
Returns the key for needle if it is found in the array, FALSE otherwise.
So you should change your code to:
$result = array_search($request_IP, $list_Array);
if ($result === false) {
// Not found
echo "FAIL";
exit;
} else {
// $result is the key of the element in the array
echo $result . "\n";
}
Example A matches properly, it returns index 0.
0 is a falsy variable. 0 == false.
Look at https://secure.php.net/manual/en/types.comparisons.php what kind of values match to which result when doing loose comparisan(two ==) in the boolean column
You can better flip the if statements, to test for the false first.
We don't need an "else" here because either the code will abort in the if statement, or it will continue.
Saves an indentation level.
if($result === false) {
echo "FAIL";
exit;
}
// success
Three === means an exact match on value AND type
That's because in section A,
array_search($request_IP, $list_Array) will return zero.
so next condition line would compile as following:
if ($result) // if (0)
this condition will always return false.
To fix this issue. you have to use following line
if ($result === FALSE)
Because in your first example array_search will return 0 - because the first occurence of 8.8.8.8 is the first item. PHP is designed "weakly", so an assertion of "0" and boolean false will be true (false == 0) and an assertion of 1 and true will also be true (true == 1). This can be very tricky - as for example strpos returns 0 if a pattern is in the beginning of a string, in that case you would need to write your condition like (strpos($string, $search) !== false) - simply checking the return type "weakly" would result in a logic error (!strpos($string, $search).
You will have to adopt the condition.
I would recommend to use in_array
if (in_array($request_IP, $list_Array) === true)
will do
You should also have a look at this question:
What are the benefits (and drawbacks) of a weakly typed language?
Weak types is not bad design, its concept, if you use PHP or any other weakly typed language for business logic, you will need to be extra careful, using strict comparison only (=== instead of ==, !== instead of != and explicit comparison instead of negation) is a good start.
This question already has answers here:
The 3 different equals
(5 answers)
Closed 9 years ago.
Does it really matter to put variables after == or === when doing comparisons?
if (null == $var) {
}
if ($var == null) {
}
I've constantly seen coders prefer this way, is it for speed difference?
Updates:
Sorry I didn't make my question clear, what I want to know is not the different between == and ===, but expressions like null == $var and $var == null, so I've changed the code example.
Conslusion:
No functional or performance difference. Some consider it a best practice or simply a coding style. BTW it has a cool name: Yoda Conditions :)
FYI: PHP error messages use this style, e.g.
PHP Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
Don't know why this question is marked duplicated to (The 3 different equals) not (What's the difference between 'false === $var' and '$var === false'?)
It prevents typos which cause very hard to debug bugs. That's in case you accidentally write = instead of ==:
if ($var == null) # This is true in case $var actually is null
if ($var = null) # This will always be true, it will assign $var the value null
Instead, switching them is safer:
if (null == $var) # True if $var is null
if (null = $var) # This will raise compiler (or parser) error, and will stop execution.
Stopping execution on a specific line with this problem will make it very easy to debug. The other way around is quite harder, since you may find yourself entering if conditions, and losing variable's values, and you won't find it easily.
I think that the following code will explain it:
echo (( 0 == NULL ) ? "0 is null" : "0 is not null") ."\n";
echo (0 === NULL) ? "0 is null" : "0 is not null" ;
it will output:
0 is null
0 is not null
The === operator checks for both value and type, but 0 is a number while NULL is of type NULL
The == operator checks only for value and zero can be casted to "false" or "null" hence the "truthy" that we get for the first line
Compare results from this to ifs.
echo "Test '1abc' == 1 - ";
if ('1abc' == 1) {
echo 'ok';
} else {
echo 'fail';
}
echo "\nTest '1abc' === 1 - ";
if ('1abc' === 1) {
echo 'ok';
} else {
echo 'fail';
}
Then read this page http://php.net/manual/en/language.types.type-juggling.php it's very interesting lecture ;)
This question already has answers here:
PHP considers null is equal to zero
(11 answers)
Closed 9 years ago.
I wrote a simple test:
$test = null;
if ($test == null) print 'is null';
else print 'not null';
This prints out: "is null". Problem is, I changed it to this:
$test = 0;
if ($test == null) print 'is null';
else print 'not null';
And it still prints out null? Why?
That's because PHP performs a loose comparison when you use ==, i.e. it will attempt to coerce one of the operands into the type of the other if they're not the same.
For example:
array() == false
null == ''
0 == '0'
To compare the value and type together you need the === (triple equals operator), e.g.
if (null === 0) {
// this can never happen
}
This be the burden of using a dynamically typed language :)
Use is_null function
is_null($test)
Test
$test = 0;
if (is_null($test)) print 'is null';
else print 'not null';
// Return not null
PHP treats 0 as NULL.
To check if a value is NULL, you can either use is_null() function or use === in your conditional statement:
$test = 0;
if ($test === null) print 'is null';
else print 'not null';
See a demo here.
Refer to the PHP Manual for more information.
This question already exists:
Closed 10 years ago.
Possible Duplicate:
php == vs === operator
i have the following code fragment and it doesn't make sense to me why would NULL be evaluated in 3 different ways. Consider the variable $uploaded_filenames_array as UNKNOWN - we don't know whether it's still an array or a NULL. That's what we are trying to check.
//-----------------------------------------------
if (is_null($uploaded_filenames_array)){
echo "is_null";
}
else{
echo "is_NOT_null";
}
//-----------------------------------------------
if ($uploaded_filenames_array == NULL){
echo "NULL stuff";
}
else{
echo "not NULL stuff";
}
//-----------------------------------------------
if ($uploaded_filenames_array === NULL){
echo "NULL identity";
}
else{
echo "not NULL identity";
}
//-----------------------------------------------
i am getting the following response:
is_NOT_null
NULL stuff
not NULL identity
can somebody help to understand what is the programmatic difference between these 3 ways of checking NULL?
is_null($a) is same as $a === null.
($a === null is bit faster than is_null($a) for saving one function call, but it doesn't matter, just choose the style you like.)
For the difference of === and ==, read PHP type comparison tables
$a === null be true only if $a is null.
But for ==, the below also returns true.
null == false
null == 0
null == array()
null == ""
You should read this http://php.net/manual/en/language.operators.comparison.php. Also no need to use is_null function to check only on NULL. === is faster...
The === operator tests for the same value and the same TYPE. An empty string might evaluate to null, but it is not of the null type - hence this fails.
The == operator basically checks to see if they are pretty much the same - by that, do the evaluate to the same value. Being empty, this will evaluate to null, hence this fails.
The is_null function does a fairly thorough check - much more like the === operator.
== checks if the value is equal e.g.:
>> "123" == 123
<< true
=== checks if the value & type are equal e.g.:
>> "123" === 123
<< false