How to convert string to boolean php

laukok picture laukok · Sep 7, 2011 · Viewed 320.1k times · Source

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

Brad picture Brad · Feb 25, 2013

This method was posted by @lauthiamkok in the comments. I'm posting it here as an answer to call more attention to it.

Depending on your needs, you should consider using filter_var() with the FILTER_VALIDATE_BOOLEAN flag.

filter_var(    true, FILTER_VALIDATE_BOOLEAN); // true
filter_var(    'true', FILTER_VALIDATE_BOOLEAN); // true
filter_var(         1, FILTER_VALIDATE_BOOLEAN); // true
filter_var(       '1', FILTER_VALIDATE_BOOLEAN); // true
filter_var(      'on', FILTER_VALIDATE_BOOLEAN); // true
filter_var(     'yes', FILTER_VALIDATE_BOOLEAN); // true

filter_var(   false, FILTER_VALIDATE_BOOLEAN); // false
filter_var(   'false', FILTER_VALIDATE_BOOLEAN); // false
filter_var(         0, FILTER_VALIDATE_BOOLEAN); // false
filter_var(       '0', FILTER_VALIDATE_BOOLEAN); // false
filter_var(     'off', FILTER_VALIDATE_BOOLEAN); // false
filter_var(      'no', FILTER_VALIDATE_BOOLEAN); // false
filter_var('asdfasdf', FILTER_VALIDATE_BOOLEAN); // false
filter_var(        '', FILTER_VALIDATE_BOOLEAN); // false
filter_var(      null, FILTER_VALIDATE_BOOLEAN); // false