Wednesday, June 5, 2019

How to convert string to boolean php



How can I convert string to boolean?



$string = 'false';

$test_mode_mail = settype($string, 'boolean');

var_dump($test_mode_mail);

if($test_mode_mail) echo 'test mode is on.';


it returns,




boolean true




but it should be boolean false.


Answer



Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP (taken from the documentation for empty):




  1. "" (an empty string);

  2. "0" (0 as a string)



If you need to set a boolean based on the text value of a string, then you'll need to check for the presence or otherwise of that value.



$test_mode_mail = $string === 'true'? true: false;


EDIT: The above code is intended for clarity of understanding. In actual use the following code may be more appropriate:



$test_mode_mail = ($string === 'true');

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...