I am wondering why following statement in PHP is returning true?
true>=4
for example such line will echo 1
echo true>=4;
Can anyone explain me the logic behind this?
4 is also true (because it's non-zero), and true is equal to true, so it's also greater than or equal to true.
If a bool or null is compared to anything other than a string, that thing is cast to a bool. See the docs.
In addition to Davids answer, I thought to add something to give a little more depth.
PHP unlike other programming languages, if your not careful with your operators/syntax you can fall into tricky pot holes like the one you experience.
As David said,
4 is also true (because it's non-zero), and true is equal to true, so
it's also greater than or equal to true.
Take this into account
True is greater than false.
true = 1
false = 0
So take this for example:
$test = 1;
if ($test == true){
echo "This is true";
}else{
echo "This is false";
}
The above will output
This is true
But if you take this:
$test = 1;
if ($test === true){
echo "This is true";
}else{
echo "This is false";
}
The above will output:
This is false
The added equals sign, looks for an exact match, thus looking for the integer 1 instead of PHP reading 1 as true.
I know this is a little off topic, but just wanted to explain some pot holes which PHP contains.
I hope this is some help
Edit:
In response to your question:
echo true>=4;
Reason you are seeing 1 as output, is because true/false is interpreted as numbers (see above)
Regardless if your doing echo true>=4 or just echo true; php puts true as 1 and false as 0
Related
I eval $var using
if(empty($_GET['var'])){
...
}
I take TRUE from
https://myweb.com/?var=0
I take FALSE from
https://myweb.com/?var=00
The empty pseudo-function shares its logic with casting to boolean - if something is equivalent to "false", it is considered "empty".
The list of values which are considered "empty" is intended to be helpful, but is occasionally confusing, because there isn't really one perfect answer. Starting off with integers, it seems reasonable that 0 is "empty", but for instance 1 is not. Because user input almost always comes in the form of strings (particularly on the web, where PHP is most at home), it's also useful for the string "0" to behave the same as the integer 0.
On the face of it, "00" should also be equivalent to 0, and therefore "empty", but now things start getting messy: if you convert the string "hello" to an integer, that is also 0, so is "hello" also empty? That wouldn't be very useful.
The truth is, casts such as this can only really work one of two ways:
Throw an error on any conversion which is not 100% unambiguous.
Pick a set of compromises which is mostly useful, but not entirely consistent.
PHP picked the second route, and the difference between empty("0") and empty("00") is one of the side effects of the particular compromise chosen. Other languages which took a similar route (e.g. Perl, JavaScript) have different compromises, with different surprising outcomes.
See also my answer to a similar question here.
Because 0 gives empty in PHP if you check without type, but I think 00 type-cast to a string value and thus it's not empty.
You can strict check with type via the operator ===
I think it's probably because you are receiving the 00 as string value in your code. Because 0 and 00 are both considered as empty by the empty function in PHP. Try executing the code below in one of your PHP's to understand better. You can even check out the sandbox link.
<?php
$a = 0;
$b = 00;
$c = '00';
if(empty($a)) echo 'empty a';
if(empty($b)) echo 'empty b';
if(empty($c)) echo 'empty c';
?>
Check the documentation of empty() function, there are a list of values that are considered as empty by it.
The empty() function checks whether a variable is empty or not.
This function returns false if the variable exists and is not empty,
otherwise it returns true.
The following values evaluates to empty:
0
0.0
"0"
""
NULL
FALSE
array()
Additionally, when you are dealing with numeric check, you should always typecast the value to integer and then compare if it's 0 or not. This would be the ideal approach.
<?php
$a = 0;
$b = '0';
$c = '00';
$d = 1;
$e = '1';
if(!intval($a)) echo 'empty a ';
if(!intval($b)) echo 'empty b ';
if(!intval($c)) echo 'empty c ';
if(!intval($d)) echo 'empty d ';
if(!intval($e)) echo 'empty e ';
?>
I have the following PHP (the server is running version 5.3.x) in a script which is giving me a result that I am having trouble understanding. The general idea of this code is that I have a "normal mode", and two maintenance modes. In the first maintenance mode, data is only evaluated and can be viewed by an admin but is not stored to the database. If I set $maintenance_mode_enabled = 2;, then the same "preview" output should be displayed but only SOME specific updates to the database should be processed. The reason I added the ==2 comparison is because I found the need for a third option after I had setup the true/false for the basic default maintenance mode. At any rate, I noticed 18 records on my last maintenance_mode_enabled = true; run that were partially updated during the process, just as though I had set maintenance_mode_enabled = 2;.
$maintenance_mode_enabled = true;
if ($maintenance_mode_enabled){
echo "Case 0\n";
}
if (!$maintenance_mode_enabled){
echo "Case 1\n";
}
if ($maintenance_mode_enabled == 2){
echo "Case 2\n";
}
The output I get is:
Case 0
Case 2
From what I understood, true (being boolean) is definitely not equal to 3. I am familiar with some oddities when comparing false, NULL and 0, but this problem with integers and TRUE is entirely new to me.
Any ideas as to why this isn't working? I realize that I can just as easily change $maintenance_mode_enabled to an integer instead of a bolean by default, and set it as either 0, 1 or 2 to get the desired results, but I really want to understand WHY this seems to defy logic.
The reason this happens is because you're comparing a boolean to an integer. As with many languages, at the core of the comparison function it's casting the second part of your comparison to a boolean. Any non-NULL, non-zero, non-empty or non-false value, in this case 2 is "true."
As the previous answer mentions I would change the code to use strict comparison. I would also change from three separate if-statements to one if-elseif statement:
if ($maintenance_mode_enabled === true) {
// catches only true not > 0
echo "Case 0\n";
} elseif ($maintenance_mode_enabled === false) {
// catches only true not = 0
echo "Case 1\n";
} elseif ((int)$maintenance_mode_enabled === 2) {
echo "Case 2\n";
}
I recommend this change because maintenance mode can only have one value.
EDIT
I didn't realize true and 2 could coexist. You could do:
if ($maintenance_mode_enabled) {
echo "Case 0\n";
if (2 === (int)$maintenance_mode_enabled) {
echo "Case 2\n";
}
} else {
echo "Case 1\n";
}
Use the === operator for true otherwise all non 0 / null / false will be true.
Use the === operator for false otherwise all equal to 0 / false / null will show as "false"
The following will output Case 0
<?php
$maintenance_mode_enabled = true;
if ($maintenance_mode_enabled === true){
// catches only true not just > 0
echo "Case 0\n";
}
elseif (!$maintenance_mode_enabled === false){
// catches only false not including = 0
echo "Case 1\n";
}
elseif ($maintenance_mode_enabled == 2){
echo "Case 2\n";
}
?>
Oh, NOW I get it. It seems the problem here is that when I do the loose (==) comparison of a boolean with an integer, the type casting is converting the integer into a boolean, thus resulting in 2 being equal to true - since both are being tested as booleans. The solution is to use strict (===) comparison, so that both must be of the same type... i.e.: 2 (integer), is not exactly the same as true, since true is is of a different type - boolean.
<?php
isInt("4");
isInt("Test");
function isInt($id){
echo $id." ".(int)$id;
if($id == (int)$id)echo "True.<br />";
else echo "False.<br />";
}
?>
The output results in:
4 4 True.
Test 0 True.
You'll notice the 2nd results in true, which by the output, it should echo false.
I realize there is a built in function in php is_int().
I also realize that in the if statement if I put a 3rd equals sign: if($id === (int)$id) then it will return false for the 2nd one, but it will also return false for the 1st one too.
Can someone explain to me why PHP does this, and maybe a fix for this? (I am running PHP 5.4.22)
Basically what I want to accomplish is isInt("4") to echo true, isInt(4) to echo true, and isInt("Text") to echo false;
If you use the triple equals, it checks the type along with the result.
For the first one, "4" is a string, not an int (the literal 4 is an int, but since you're using quotes, it's a string).
For the second one, "Test" is a string as well.
For your second version:
$id = 'Test';
'Test' == (int)'Test';
'Test' == 0
0 == 0
TRUE
Strings which contain no digits at the beginning of the string will always get auto-converted to integer 0 when used in an integer context.
If you'd had 123Test instead:
$id = '123Test';
'Test' == int('Test');
'Test' == 123
0 == 123
FALSE
to get desired value , check this..
if($id === (int)$id)echo "True.<br />";
I have the following code:
$posthandlerResult = reserveerForm_posthandler(decideWhichSectionlist());
if($posthandlerResult=='go2paypage'){
echo 1;
}elseif($posthandlerResult===true){
echo 2;
}else{
echo 3;
}
This is the value of $posthandlerResult (I did this before I did the if/else):
var_dump( $posthandlerResult); // -> bool(true)
What am I expecting? An echo with the number 2. However, im getting number 1. I've been looking at this too long now, why wont this work?
You may use the ===-operator to check for the correct type, too.
The == checks, if the two expressions evaluate to the same value. Interpreted as a bool your string evaluates to true.
The first of your operands is a bool-value, so the second operand is interpreted as a bool, too. A non-empty and not zero string evaluates to boolean true.
You can look up the operator-behaviour for string and bool comparisons here: http://www.php.net/manual/en/language.operators.comparison.php
When using 'if (true == 'someString')', any string that isn't empty or the value 0, will equate to true (so this if statement will be true), see here:
http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
Code will explain more:
$var = 0;
if (!empty($var)){
echo "Its not empty";
} else {
echo "Its empty";
}
The result returns "Its empty". I thought empty() will check if I already set the variable and have value inside. Why it returns "Its empty"??
http://php.net/empty
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Note that this is exactly the same list as for a coercion to Boolean false. empty is simply !isset($var) || !$var. Try isset instead.
I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.
A snippet:
Expression | empty($x)
----------------+--------
$x = ""; | true
$x = null | true
var $x; | true
$x is undefined | true
$x = array(); | true
$x = false; | true
$x = true; | false
$x = 1; | false
$x = 42; | false
$x = 0; | true
$x = -1; | false
$x = "1"; | false
$x = "0"; | true
$x = "-1"; | false
$x = "php"; | false
$x = "true"; | false
$x = "false"; | false
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
In case of numeric values you should use is_numeric function:
$var = 0;
if (is_numeric($var))
{
echo "Its not empty";
}
else
{
echo "Its empty";
}
Use strlen() instead.
I ran onto the same issue using 1/0 as possible values for some variables.
I am using if (strlen($_POST['myValue']) == 0) to test if there is a character or not in my variable.
I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements, 0 (or the string '0' which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.
using empty() first and then strlen() is your best best if you need this as well, as:
if(!empty($var) && strlen($var)){
echo '"$var" is present and has a non-falsey value!';
}
From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.
empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()
To accept 0 as a value in variable use isset
Check if variable is empty
$var = 0;
if ($var == '') {
echo "empty";
} else {
echo "not empty";
}
//output is empty
Check if variable is set
$var = 0;
if (isset($var)) {
echo "not empty";
} else {
echo "empty";
}
//output is not empty
It 's working for me!
//
if(isset($_POST['post_var'])&&$_POST['post_var']!==''){
echo $_POST['post_var'];
}
//results:
1 if $_POST['post_var']='1'
0 if $_POST['post_var']='0'
skip if $_POST['post_var']=''
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but
without a value in a class)
From PHP Manual
In your case $var is 0, so empty($var) will return true, you are negating the result before testing it, so the else block will run giving "Its empty" as output.
From manual:
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string) NULL
FALSE array() (an empty array) var
$var; (a variable declared, but
without a value in a class)
More: http://php.net/manual/en/function.empty.php
You need to use isset() to check whether value is set.
Actually isset just check if the variable sets or not.In this case if you want to check if your variable is really zero or empty you can use this example:
$myVar = '';
if (empty($myVar))
{
echo "Its empty";
}
echo "<br/>";
if ($myVar===0)
{
echo "also zero!";
}
just for notice $myVar==0 act like empty function.
if (empty($var) && $pieces[$var] != '0') {
//do something
}
In my case this code worked.
empty should mean empty .. whatever deceze says.
When I do
$var = '';
$var = '0';
I expect that var_dump(empty($var)); will return false.
if you are checking things in an array you always have to do isset($var) first.
use only ($_POST['input_field_name'])!=0 instead of !($_POST['input_field_name'])==0 then 0 is not treated as empty.
Not sure if there are still people looking for an explanation and a solution. The comments above say it all on the differences between TRUE / FALSE / 1 / 0.
I would just like to bring my 2 cents for the way to display the actual value.
BOOLEAN
If you're working with a Boolean datatype, you're looking for a TRUE vs. FALSE result; if you store it in MySQL, it will be stored as 1 resp. 0 (if I'm not mistaking, this is the same in your server's memory).
So to display the the value in PHP, you need to check if it is true (1) or false (0) and display whatever you want: "TRUE" or "FALSE" or possibly "1" or "0".
Attention, everything bigger (or different) than 0 will also be considered as TRUE in PHP. E.g.: 2, "abc", etc. will all return TRUE.
BIT, TINYINT
If you're working with a number datatype, the way it is stored is the same.
To display the value, you need to tell PHP to handle it as a number. The easiest way I found is to multiply it by 1.
proper example. just create int type field( example mobile number) in the database and submit an blank value for the following database through a form or just insert using SQL. what it will be saved in database 0 because it is int type and cannot be saved as blank or null. therefore it is empty but it will be saved as 0. so when you fetch data through PHP and check for the empty values. it is very useful and logically correct.
0.00, 0.000, 0.0000 .... 0.0...0 is also empty and the above example can also be used for storing different type of values in database like float, double, decimal( decimal have different variants like 0.000 and so on.