March 7, 201115 yr Having a bit of a mental block. Is it possible to convert a string to a boolean in PHP? Typecasting to int always returns 0 whereas bool always returns 1. $string1 = "true"; $string2 = "false"; echo (bool)$string1, " | ", (bool)$string2; echo "<br />"; echo (int)$string1, " | ", (int)$string2; outputs: 1 | 1 0 | 0 I know I can use conditions but I was wondering if theres a quick way to do it. Cheers
March 7, 201115 yr No, thats the expected result when type juggling those values. You'd need to use a conditional statement to return a boolean from those strings. The only thing php will convert to a boolean from string is '0' and '' for false, anything else will be cast as true.
March 7, 201115 yr No, thats the expected result when type juggling those values. You'd need to use a conditional statement to return a boolean from those strings. The only thing php will convert to a boolean from string is '0' and '' for false, anything else will be cast as true. He's right, you know - I just checked. Ha. I'd set up an Orwellian true = false example if I could be arsed.
May 30, 201115 yr Having a bit of a mental block. Is it possible to convert a string to a boolean in PHP? Typecasting to int always returns 0 whereas bool always returns 1. $string1 = "true"; $string2 = "false"; echo (bool)$string1, " | ", (bool)$string2; echo "<br />"; echo (int)$string1, " | ", (int)$string2; outputs: 1 | 1 0 | 0 I know I can use conditions but I was wondering if theres a quick way to do it. Cheers This is what I do... $str = 'false'; $bool = ($str == 'true'); //proof echo ($bool)? 'Boolean TRUE' : 'Boolean FALSE';
Create an account or sign in to comment