I have acrossed some really weird behaviour in PHP statment when having example below:
Logically it shouldn't return 1 in this context. Why this is happening ? Just was wondering.
$test = 0;
var_dump($test); // gives int 0
$test = ($test == 'test') ? 1 : 0;
var_dump($test); //gives int 1
This is because of type juggling. 'test' is equal to 0 because (int)'test' actually is 0. Thus, your condition is true and 1 is the result.
In your particular case you may want to know how PHP converts strings to numbers.
Just try with === to compare also type of values:
$test = ($test === 'test') ? 1 : 0;
Related
I want to convert String variable 'true' or 'false' to int '1' or '0'.
To achieve this I'm trying like this
(int) (boolean) 'true' //gives 1
(int) (boolean) 'false' //gives 1 but i need 0 here
I now I can using array like array('false','true');
or using if($myboolean=='true'){$int=1;}
But this way is less efficient.
Is there another more efficient way like this (int) (boolean) 'true' ?
I know this question has been asked. but I have not found the answer
Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP.
Depending on your needs, you should consider using filter_var() with the FILTER_VALIDATE_BOOLEAN flag.
(int)filter_var('true', FILTER_VALIDATE_BOOLEAN);
(int)filter_var('false', FILTER_VALIDATE_BOOLEAN);
Why not use unary operator
int $my_int = $myboolean=='true' ? 1 : 0;
the string "false" is truthy. That's why (int) (boolean) "false" return 1 instead of 0. If you want to get a false boolean value from a string, you can pass an empty string (int) (boolean) "". More info here.
PHP
$int = 5 - strlen($myboolean);
// 5 - strlen('true') => 1
// 5 - strlen('false') => 0
JAVASCRIPT
// ---- fonction ----
function b2i(b){return 5 - b.length}
//------------ debug -----------
for(b of ['true','True','TRUE','false','False','FALSE'])
{
console.log("b2i('"+b+"') = ", b2i(b));
}
Try this:
echo (int) (boolean) '';
$variable = true;
if ($variable) {
$convert = 1;
}
else {
$convert = 0;
}
echo $convert
Normally just $Int = (int)$Boolean would work fine, or you could just add a + in front of your variable, like this:
$Boolean = true;
var_dump(+$Boolean);
ouputs: int(1);
also, (int)(bool)'true' should work too
In the file defines.php, I have define("YES",1);.
I am including this file in the login.php page as
require_once('/defines.php');
where I have this check if ($row['registered'] === YES). This is not evaluating to true. If I use double equals, it works. I did
echo $row['registered'];
echo YES;
and I am getting the output as
1
1
On my localhost machine, however, === is working fine. Why is this strange behaviour? Is there any dependency on production server?
PS : My hosing server is using PHP v5.4
EDIT
Var dump :
string(1) "1" int(1)
But I have tinyint type in database, why I am getting string data type?
Your database driver returns the value of registered as string
you can either typecast your integer values and them compare them
using ===
(int)$row['registered']
or use the == operator instead
Check this answer https://stackoverflow.com/a/80649/2255129 for the differences of === and ==
the problem is
$var1 = '1';
$var2 = 1;
// this will be right
if ( $var1 == $var2 )
{ echo "'1' = 1"; }
// This will never be right
if ( $var1 === $var2 )
{ echo "'1' != 1"; }
in PHP you can not use === to match string and int or boolean.
eg.
1 == '1' = true
1 === '1' = false
1 === 1 = true
true === 1 = false
true == 1 = true
thats mean if you use === and not == its need to be same type like string === string or int === int
you need to use == if you want to match int and string, i do not recommend you combine string and int in a if statement.
convert you string to int, and make a match agin like this
$var1 = (int) $row['registered'];
$var2 = (int) YES;
if ( $var1 === $var2 )
{ echo 'your right'; }
else
{ echo 'you got a problem'; }
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.
I have the following code:
<?php
$val = 0;
$res = $val == 'true';
var_dump($res);
?>
I always was under impression that $res should be 'false' as in the above expression PHP would try to type cast $val to boolean type (where zero will be converted as false) and a string (non-empty string is true). But if I execute the code above output will be:
boolean true
Am I missing something? Thanks.
In PHP, all non-empty, non-numeric strings evaluate to zero, so 0 == 'true' is TRUE, but 0 === 'true' is FALSE. The string true has not been cast to a boolean value, but is being compared as a string to the zero. The zero is left as an int value, rather than cast as a boolean. So ultimately you get:
// string 'true' casts to int 0
0 == 0 // true
Try this:
echo intval('true');
// 0
echo intval('some arbitrary non-numeric string');
// 0
Review the PHP type comparisons table. In general, when doing boolean comparisons in PHP and types are not the same (int to string in this case), it is valuable to use strict comparisons.
Because $val is the first operator PHP converts the string true to an integer which becomes 0. As a result 0 ==0 and your result is true;
Try this
<?php
$val = 1;
$res = (bool)$val == 'true';
var_dump($res);
?>
I've always done this: if ($foo !== $bar)
But I realized that if ($foo != $bar) is correct too.
Double = still works and has always worked for me, but whenever I search PHP operators I find no information on double =, so I assume I've always have done this wrong, but it works anyway. Should I change all my !== to != just for the sake of it?
== and != do not take into account the data type of the variables you compare. So these would all return true:
'0' == 0
false == 0
NULL == false
=== and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:
'0' === 0
false === 0
NULL === false
You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():
// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false); // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
!== should match the value and data type
!= just match the value ignoring the data type
$num = '1';
$num2 = 1;
$num == $num2; // returns true
$num === $num2; // returns false because $num is a string and $num2 is an integer
$a !== $b TRUE if $a is not equal to $b, or they are not of the same type
Please Refer to http://php.net/manual/en/language.operators.comparison.php
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.