<?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 />";
Related
I'm begenning at PHP , I was poking around my code and learning about List of comparison operators , however I'll try out to put echo before my comparasion operators and I've received this result : 1 then I though the reason is comparasion true equal to 1, else equal to 0 , in this moment seemed me somethig kinda python, yet I just got the 1 . why not 0 as result ?
Is attached my question
You're printing a boolean value. The value is converted to a string where 1 represents true and a blank string represents false.
From the manual:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.
http://php.net/manual/en/language.types.string.php
You could use the ternary operator to output the string true or false where appropriate. Example:
echo (10 >= 12) ? 'true' : 'false';
when print boolean value in php it will print 1 if TRUE and "" if FALSE.
if you want to print 0 if FALSE then you can convert into int.
in your case you can use like this
$bool = 10 >= 12;
echo (int)$bool;
it will return 0.
<?php
echo 10>=9 // print 1 as it is true
echo 11>3 // print 1
echo 11 == 11 // print 1
echo 10>=12 // print nothing because it is false
This happening becuase a boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string).
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
this is code:
$s = 0;
$d = "dd";
if ($s == $d) {
var_dump($s);
die(var_dump($d));
}
result is:
int 0
string 'dd' (length=2)
Please explain why.
why ($s == $d) results as true?
Of course, if === is used it will results as false but why this situation requires ===?
Shouldn't it be returned false in both situations?
Because (int)$d equals with 0 and 0=0
you must use strict comparison === for different character tyes (string) with (int)
Your $d is automatically converted to (int) to have something to compare.
When you compare a number to a string, the string is first type juggled into a number. In this case, dd ends up being juggled into 0 which means that it equates to true (0==0).
When you change the code to:
<?php
$s = 1;
$d = "dd";
if ($s == $d)
{
var_dump($s);
die(var_dump($d));
}
?>
You will find that it doesn't pass the if statement at all.
You can more details by reading up on comparison operators and type juggling.
The string "dd" is converted to int, and thus 0.
Another example :
if ( "3kids" == 3 )
{
return true;
}
And yes, this returns true because "3kids" is converted to 3.
=== does NOT auto convert the items to the same type.
Also : 0 == false is correct, but 0 === false is not.
See : http://php.net/manual/en/language.types.type-juggling.php
The string will try to parsed into a number, returns 0 if it is not in right number format.
As seen in the php website :
http://php.net/manual/en/language.operators.comparison.php
var_dump(0 == "a"); // 0 == 0 -> true
In PHP, == should be pronounce "Probably Equals".
When comparing with ==, PHP will juggle the file-types to try and find a match.
A string with no numbers in it, is evaluated to 0 when evaluated as an int.
Therefore they're equals.
if(NULL ==0){
echo "test". NULL;//output is test
echo "<br>";
echo "test". 0;//output is test0
}
If condition say both null and 0 are equal.But why did i get this result?
You have used Loose comparison == . If you use Strict comparison === then you will find the differences.
Read more :
type comparison table
NULL in PHP
Because it depends if you are looking at 0 as the number zero (as in nothing) or a string (as in the character '0').
NULL in PHP has the following properties:
NULL == NULL is true,
NULL == FALSE is true.
And in line with the relational model, NULL == TRUE fails
Over here you are comparing NULL to false whose output is true in PHP
As Nick already said: in this case, you are adding the value 0 to a string that makes it also a string. That's why you get the value test0.
Also, in your if, you are checking for zero value, not a strict true or false statement:
<?php
if( NULL == 0 ) {
echo "test" . NULL;
echo "<br>";
echo "test" . 0;
}
?>
Output:
test
test0
Now try it like this:
<?php
if( NULL === 0 ) {
echo "test" . NULL;
echo "<br>";
echo "test" . 0;
}
?>
You will see, that you get no output, because now the if statement is false.
NULL has no value, in your comparison it is evaluating to False, and 0 is also evaluated as False (so False == False, which is True), which is why the body of the loop executes.
NULL explicitly means "no value". See the documentation for what exactly NULL is.
because if you concat a string with NOTHING (null) the string will remain at it is, if you concat with the integer "0", it will be casted to string (auto-boxing) and concated to the original string...
normal behaviour?
and "null == 0" -> true, but "null === 0" -> false...
you have to check not only the VALUE (which will be "zero" for both itc), you have to check TYPE equality too with "==="
Because, a NULL string is nothing to be printed. Hence the first echo statement, concatenates:
"test" . NULL => "test" Then Nothing
While the 0 is a logical NULL, but in case of String it prints as 0.
In PHP, if you compare any value to a number, the value will be typecasted to Int or Float, and then the comparison will be done. In your case, the NULL is first typecasted to Int, which produces 0, and then compared, givng TRUE. Check PHP type comparison and type juggling.
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.