Reputation: 589
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'
?
Upvotes: 8
Views: 11983
Reputation: 1621
$variable = true;
if ($variable) {
$convert = 1;
}
else {
$convert = 0;
}
echo $convert
Upvotes: 0
Reputation: 31397
Why not use unary operator
int $my_int = $myboolean=='true' ? 1 : 0;
Upvotes: 2
Reputation:
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));
}
Upvotes: -1
Reputation: 218
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);
Upvotes: 13
Reputation: 115
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
Upvotes: -1