Sate Wedos
Sate Wedos

Reputation: 589

Convert String 'true' or 'false' to interger '1' or '0'

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

Upvotes: 8

Views: 11983

Answers (7)

LeviZoesch
LeviZoesch

Reputation: 1621

$variable = true;

if ($variable) {
     $convert = 1;
}
else {
    $convert = 0;
}

echo $convert

Upvotes: 0

Ashish Tiwari
Ashish Tiwari

Reputation: 2277

Try this:

echo (int) (boolean) '';

Upvotes: 0

Ravi
Ravi

Reputation: 31397

Why not use unary operator

int $my_int = $myboolean=='true' ? 1 : 0;

Upvotes: 2

user3114072
user3114072

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

Farhad Mortezapour
Farhad Mortezapour

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

TheRealOrange
TheRealOrange

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

Andy Aldo
Andy Aldo

Reputation: 890

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.

Upvotes: 1

Related Questions