Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 928
sate wedos Avatar asked Oct 22 '17 04:10

sate wedos


2 Answers

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);
like image 150
Farhad Mortezapour Avatar answered Sep 29 '22 07:09

Farhad Mortezapour


Why not use unary operator

int $my_int = $myboolean=='true' ? 1 : 0;
like image 45
Ravi Avatar answered Sep 29 '22 07:09

Ravi