How can PHP 5.3 think 0 is null? [duplicate] - php

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.

Related

PHP if condition microoptimalisation [duplicate]

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 ;)

PHP8 compare 0 with an empty string, what is the logic behind that [duplicate]

This question already has an answer here:
Empty string comparison to zero gives different result in PHP 8 than in previous versions
(1 answer)
Closed 1 year ago.
in PHP 8 why comparing 0 with an empty string, surprised me.
I can't understand the logic.
$a = 0;
$b = "";
echo ($a == false) ? "yes a is False<br>" : "no<br>";
echo ($b == false) ? "yes b is False<br>" : "no<br>";
echo ($a == $b) ? "yes a equals False and b equals to False" : "no, False is not equal to False!!!, there is a problem";
the output is "no, False is not equal to False!!!, there is a problem"
in the above code, I expected to give yes a equals False and b equals False but PHP surprised me.
can you help me to understand why the output is no?
if(false == false) it should return true and it works fine.
but,
if("" == 0) it should return true too, but it will return false, even "" and 0 are false. I want to know why???
I want the logic behind this.
I use PHP 8.0.2
There is an incompatibility in PHP 8. You can find it here: https://www.php.net/manual/en/migration80.incompatible.php
I recommend you cast your values before comparing
if (boolval($a) == boolval($b)) {
// do stuff
}
I think that happen because PHP8.
I try this code
$a = 0;
$b = "";
$result = ($a == $b) ? "yes a equals False and b equals to False" : "no, False is not equal to False!!!, there is a problem";
echo($result);
In PHP5 and PHP7 its return "yes a equals False and b equals to False" but in PHP8 its return "no, False is not equal to False!!!, there is a problem"
you can try its in PHP online Sandbox

If statement is true OR not false [duplicate]

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.

Does variables' order matter when doing == and === comparisons? [duplicate]

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 ;)

difference between is_null "== NULL" and "=== NULL" in PHP [duplicate]

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

Categories