Logic in PHP, why is this happening? - php

function x() {return -1;}
echo x();
echo "<br>";
if(x()) {echo "True";} else {echo "False";}
output:
-1
True
Why am I getting 'True' outputted, surely the if() test would fail as it's negative?

That's because you can only test on true or false.
False is defined as 0, while true is defined as not 0. So -1 is just as much true as 1, 2, 3 etc.
To make sure you're getting the right result, make a real comparison.

-1 is considered TRUE in boolean context. See Converting to boolean in the PHP manual.

Only numeric 0 values are false in PHP: http://php.net/manual/en/language.types.boolean.php

0 is false and everything else is true. That's why !

In PHP a -1 is true as it isn't 0. Use a real comparison like:
if(x() <= 0) { ...do stuff... }

Have a look here:
var_dump(x()); //output: int(-1)
and casted to boolean:
var_dump((bool)x()); //output: bool(true)
-1 is not false in PHP. You could check if it's > 0?

All what is 0 is false and everything else is true. Wikipedia article about it

Converting to boolean in PHP
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
Warning
-1 is considered TRUE, like any other non-zero (whether negative or positive) number!
Source http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

Related

String as boolean in PHP [duplicate]

For the record, I know the solution is to use === instead of == .
I'm just wondering what the logic behind it is. How is it logical that 'hello' can equal TRUE?
$var = TRUE;
if($var == 'hello'){
echo 'match';
}
else{
echo 'no match';
}
The solution has been discussed, but I haven't seen any real explanation.
String value equals true
== compares just the values of the variables whereas === compares variable values and type. so for an example:
1 == 1: true
1 === "1": false // "1" is a string and 1 is an integer
when asking if a string == true, you are essientially asking if it is set. Similar functionality is behind the isset() method.
If you were to compare "hello" === true. This would be false as they are of different type and "hello" would HAVE to equal "hello"
When using == operator think in falsy and truthy terms.
So:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integers 0 and -0 (zero)
the floats 0.0 and -0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
-1 is considered TRUE, like any other non-zero (whether negative or positive) number!
Every other value is considered TRUE (including any resource and NAN).
#see: https://www.php.net/manual/en/language.types.boolean.php

How is it logical that a string equals TRUE in PHP

For the record, I know the solution is to use === instead of == .
I'm just wondering what the logic behind it is. How is it logical that 'hello' can equal TRUE?
$var = TRUE;
if($var == 'hello'){
echo 'match';
}
else{
echo 'no match';
}
The solution has been discussed, but I haven't seen any real explanation.
String value equals true
== compares just the values of the variables whereas === compares variable values and type. so for an example:
1 == 1: true
1 === "1": false // "1" is a string and 1 is an integer
when asking if a string == true, you are essientially asking if it is set. Similar functionality is behind the isset() method.
If you were to compare "hello" === true. This would be false as they are of different type and "hello" would HAVE to equal "hello"
When using == operator think in falsy and truthy terms.
So:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integers 0 and -0 (zero)
the floats 0.0 and -0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
-1 is considered TRUE, like any other non-zero (whether negative or positive) number!
Every other value is considered TRUE (including any resource and NAN).
#see: https://www.php.net/manual/en/language.types.boolean.php

The if statement doesn't work for false in php

When trying to get familiar with if statement in PHP, this happened.
First time i tried this code below.
if(true) {echo 'true';} else {echo 'false';}
And the output was true when the condition is true. Again, when the condition is false (if(false)) it echos false.
But i tried the same, using a variable as the condition, while changing the value of the variable.
$con='false';
if($con){echo 'true';} else{echo 'false';}
At this situation the output is true even when the variable value is false or true. At the same time, the if statement working fine when 1 and 0 is used instead true and false. Why is this happening?
$con='false';
That 'false' is a valid string which is not Boolean FALSE, just like $con='hi'; isn't.
$con=FALSE; //this is false now
To quote from the Manual
To specify a boolean literal, use the constants TRUE or FALSE. Both are case-insensitive.
Also read these other options that you have
When converting to boolean, the following values are considered FALSE:
◦ the boolean FALSE itself
◦ the integer 0 (zero)
◦ the float 0.0 (zero)
◦ the empty string, and the string "0"
◦ an array with zero elements
◦ an object with zero member variables (PHP 4 only)
◦ the special type NULL (including unset variables)
◦ SimpleXML objects created from empty tags
Then you observed this
At the same time, the if statement working fine when 1 and 0 is used instead true and false. Why is this happening?
This is because 0 in any form is FALSE, either string or numeric. But the text false as a string is not false for reasons mentioned above.
Also read about PHP Strict Comparisons since you're learning, because
var_dump(0==FALSE); //bool(true)
var_dump(0===FALSE); //bool(false) :)
PHP does some sneaky things in the if expression. The following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
You're actually passing a string that says the word false, rather than the value false itself. Because that isn't in the above list, it is actually considered true!
As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.
So as per docs try using
$con = false;//boolean and not a string
if($con){echo 'true';} else{echo 'false';}
When converting to boolean, the following values are considered FALSE:
◦ the boolean FALSE itself
◦ the integer 0 (zero)
◦ the float 0.0 (zero)
◦ the empty string, and the string "0"
◦ an array with zero elements
◦ an object with zero member variables (PHP 4 only)
◦ the special type NULL (including unset variables)
◦ SimpleXML objects created from empty tags
Check Docs (IF MANUAL)
You are using 'false' as a STRING variable, but that is the WORD false, not the BOOLEAN constant. Just use false
if(true) {echo 'true';} else {echo 'false';}
$con='false'; // Wrong
$con=false; // Right
if($con){echo 'true';} else{echo 'false';}
And when you are doing if statements, this will work:
if ($con == false) { echo 'false'; }
or you can use a === which compares one expression to another by value and by type.
if ($con === false) { echo 'false with type safe comparison!'; }
Use a bool instead of a string:
$con = false;
Your if statement will simply check that $con is not empty, so in your example it will always be true.
You can assign value to variable like this
$con=false;
In your second example, $con isn't the boolean false, it's a string literal 'false' (note the quotes), and any non-empty string in PHP evaluates as true.
To fix this, just drop the quotes:
$con=false; // no quotes!
if($con){echo 'true';} else{echo 'false';}
Your $con declaration is a string not a bool. So it will always return true.
To declare a boolean, use:
$con=FALSE; //or TRUE
'false' is not same as false.
if('true') or if('false') will result true always as they will be treated as strings and will be converted for comparison.
$con=false;
if($con){echo 'true';} else{echo 'false';}
Will print false
change the value of your variable to this
$con = false;

What is difference between if($a) and if($a==1)?

function foo($a)
{
if($a) {return "a";}
else if($a==2) {return "b";}
else {return "c";}
}
-----------------------------------------
function foo2($a)
{
if($a==1){return "a";}
if($a==2){return "b";}
if($a==3){return "c";}
}
when i passed value any number frim 1,2 or 3 ? it will return 1. when i pass value in function foo2 it will return value as value passed .
But why is difference coming ?
When you do something like if ($a), consider that PHP is a weak typed language. To understand what is evaluated in if ($a), see the conversion rules for booleans.
Quoting from the manual:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
All the others are considered TRUE, including -1 (remarkable!).
On the other hand, when you do if ($somevar == 1), then $somevar == 1 is already a boolean, and conversion rules don't apply.
if($a) any non-zero value is true.
if($a==1) only 1 value is true.
If $a is true, it will not return 1, and that is the difference.
if($a) means the same as: "if a is true, do this"
In PHP (and most other languages), the value of 0 means false and any other value is 'true'

How is `if (!integer) {}` evaluated?

I came across this code in a php database class:
if( !$this->_Link_ID )
Link_ID is an integer.
So does this code just check if Link_ID is not 0?
I know from experience that if a variable is type Boolean, you can just test the var like
$myBoolean = true;
if ($myBoolean){
// code
}
I didn't realise this can be done for integers.
So how is if( !$this->_Link_ID ) evaluated?
It checks if the integer is zero if it's integer. It also evaluates to truth if it's set to null and if it's unset, but in the latter case it also spits out a warning. if there was no negation, that would be a test for non-zero.
For more details see: converting to boolean:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
this is simply a silly way of check for non-zero,if LINK_ID is 0 or null or false ,it will
give true(please notice the '!') ,else if the LINK_iD is any thing it will give false
LINK_iD = 1 ,if (!LINK_ID) //this will give false
LINK_ID = 0 if (!LINK_iD) //this will give true
if( !$this->_Link_ID )
will return true if the value of $this->_Link_ID is 0, empty string or null.
If you want to check explicitly for "0" then you should use the triple equal ("===" or "!==") to test the value. like so
if($this->_Link_ID === 0)
or
if($this->_Link_ID === false)
if you only want it to return true for false, but not "0".
if (!$this->_Link_ID) will be true if $this->_Link_ID is not 0, and false if it is 0.
In PHP, you can test anything as a Boolean. A Boolean can be represented as 0 or 1, with 0 being false and 1 being true. In PHP, anything that is not 0 will be true, and anything that is 0 will be false. For example:
$string = 'This is a test.'
if ($string) echo 'Evaluated to true!';
Will print 'Evaluated to true!'. If $string does not exist, it will print nothing.
you should use
if (!is_int($var))
because
if (!$var)
checks if $var is not 0 or false
and if you want to check if $var exists you need to use this:
if (isset($var))
not only integers though
Here goes an explanation http://php.net/manual/en/language.types.type-juggling.php
And here goes a cheat-sheet http://www.php.net/manual/en/types.comparisons.php

Categories