453

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.

Neuron
  • 5,141
  • 5
  • 38
  • 59
Run
  • 54,938
  • 169
  • 450
  • 748

19 Answers19

868

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
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 6
    I really like this solution for setting booleans based on WordPress shortcode attributes that have values such as true, false, on, 0, etc. Great answer, should definitely be the accepted answer. – AndyWarren Jun 08 '17 at 17:49
  • 15
    `filter_var($answer, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)` worked even better for me. See http://php.net/manual/en/function.filter-var.php#121263 – Ryan Aug 26 '17 at 19:42
  • 2
    !! Important note !! filter_var returns also FALSE if the filter fails. This may create some problems. – AFA Med Oct 04 '17 at 10:30
  • 1
    THIS answer is the answer `filter_var($string, FILTER_VALIDATE_BOOLEAN);` usable in almost all situations. I'm surprised the OP marked the other answer as accepted. – HenryHayes Apr 04 '22 at 15:29
476

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');

or maybe use of the filter_var function may cover more boolean values:

filter_var($string, FILTER_VALIDATE_BOOLEAN);

filter_var covers a whole range of values, including the truthy values "true", "1", "yes" and "on". See here for more details.

Josh Wood
  • 461
  • 3
  • 14
GordonM
  • 31,179
  • 15
  • 87
  • 129
  • 6
    I recommend to always use strict comparison, if you're not sure what you're doing: `$string === 'true'` – Markus Hedlund Sep 07 '11 at 16:00
  • 280
    I found this - `filter_var($string, FILTER_VALIDATE_BOOLEAN);` is it a good thing? – Run Sep 07 '11 at 16:05
  • 12
    The ternary doesn't seem necessary. Why not just set $test_mode_mail to the value of the inequality? $test_mode_mail = $string === 'true' – Tim Banks Jun 05 '12 at 15:28
  • 3
    But what about 1/0, TRUE/FALSE? I think @lauthiamkok 's answer is the best. – ryabenko-pro Dec 15 '12 at 14:06
  • What if you have something like this: `$test_ = "(3 < 5)";` You wouldn't want to use `eval()` due to the security risks involved... – Philll_t Jul 26 '13 at 01:58
  • 2
    @FelipeTadeo I'm talking about how PHP evaluates strings with respect to boolean operations, I never mentioned eval() and I'd never recommending using it under any circumstances. The string "(3 < 5)" will be evaluated by PHP as boolean true because it's not empty. – GordonM Jul 26 '13 at 08:06
  • 1
    Just to clarify why triple equals is a bad idea; if ('true' === true) evaluates to false where if ('true' == true) evaluates to true. – Alex Barker Jan 25 '14 at 21:39
  • @AlexBarker Actually that's exactly why == is bad and why you should use === instead. Non-strict evaluation can cause horrid bugs such as unexpected type juggling http://stackoverflow.com/questions/4098104/odd-behaviour-in-a-switch-statement and unexpected object graph traversal resulting in endless recursion http://stackoverflow.com/questions/8460011/in-array-on-objects-with-circular-references – GordonM Jan 26 '14 at 00:11
  • I will also add the part in which you make the text lowercase (or uppercase) **strtolower(trim($string))** because if the value is 'TRUE', it won't match the 'true' string, so the result will be false – M. Marc Jan 12 '16 at 07:46
  • I think the base function boolval() should be mentioned, because its usefull when converting array values to booleans (array_map('boolval'...)., although not the question directly... – Romain Bruckert Jan 09 '19 at 11:16
44

The String "false" is actually considered a "TRUE" value by PHP. The documentation says:

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

See also Type Juggling.

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself

  • the integer 0 (zero)

  • the float 0.0 (zero)

  • the empty string, and the string "0"

  • an array with zero elements

  • an object with zero member variables (PHP 4 only)

  • the special type NULL (including unset variables)

  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

so if you do:

$bool = (boolean)"False";

or

$test = "false";
$bool = settype($test, 'boolean');

in both cases $bool will be TRUE. So you have to do it manually, like GordonM suggests.

Nhan
  • 3,595
  • 6
  • 30
  • 38
wosis
  • 1,209
  • 10
  • 14
  • 1
    Euhm, ofcourse the lower one returns false. In fact, it throws a fatal :) "Fatal error: Only variables can be passed by reference". $a = 'False'; settype($a,'boolean'); var_dump($a); will indeed return false. – Rob Oct 24 '16 at 06:55
20

When working with JSON, I had to send a Boolean value via $_POST. I had a similar problem when I did something like:

if ( $_POST['myVar'] == true) {
    // do stuff;
}

In the code above, my Boolean was converted into a JSON string.

To overcome this, you can decode the string using json_decode():

//assume that : $_POST['myVar'] = 'true';
 if( json_decode('true') == true ) { //do your stuff; }

(This should normally work with Boolean values converted to string and sent to the server also by other means, i.e., other than using JSON.)

Nishanth Shaan
  • 1,422
  • 15
  • 18
17

you can use json_decode to decode that boolean

$string = 'false';
$boolean = json_decode($string);
if($boolean) {
  // Do something
} else {
  //Do something else
}
isnvi23h4
  • 1,910
  • 1
  • 27
  • 45
12
(boolean)json_decode(strtolower($string))

It handles all possible variants of $string

'true'  => true
'True'  => true
'1'     => true
'false' => false
'False' => false
'0'     => false
'foo'   => false
''      => false
mrded
  • 4,674
  • 2
  • 34
  • 36
10

If your "boolean" variable comes from a global array such as $_POST and $_GET, you can use filter_input() filter function.

Example for POST:

$isSleeping  = filter_input(INPUT_POST, 'is_sleeping',  FILTER_VALIDATE_BOOLEAN);

If your "boolean" variable comes from other source you can use filter_var() filter function.

Example:

filter_var('true', FILTER_VALIDATE_BOOLEAN); // true
SandroMarques
  • 6,070
  • 1
  • 41
  • 46
5
filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

$string = 1; // true
$string ='1'; // true
$string = 'true'; // true
$string = 'trUe'; // true
$string = 'TRUE'; // true
$string = 0; // false
$string = '0'; // false
$string = 'false'; // false
$string = 'False'; // false
$string = 'FALSE'; // false
$string = 'sgffgfdg'; // null

You must specify

FILTER_NULL_ON_FAILURE
otherwise you'll get always false even if $string contains something else.
ybenhssaien
  • 3,427
  • 1
  • 10
  • 12
4

the easiest thing to do is this:

$str = 'TRUE';

$boolean = strtolower($str) == 'true' ? true : false;

var_dump($boolean);

Doing it this way, you can loop through a series of 'true', 'TRUE', 'false' or 'FALSE' and get the string value to a boolean.

3

Other answers are over complicating things. This question is simply logic question. Just get your statement right.

$boolString = 'false';
$result = 'true' === $boolString;

Now your answer will be either

  • false, if the string was 'false',
  • or true, if your string was 'true'.

I have to note that filter_var( $boolString, FILTER_VALIDATE_BOOLEAN ); still will be a better option if you need to have strings like on/yes/1 as alias for true.

kaiser
  • 21,817
  • 17
  • 90
  • 110
3
function stringToBool($string){
    return ( mb_strtoupper( trim( $string)) === mb_strtoupper ("true")) ? TRUE : FALSE;
}

or

function stringToBool($string) {
    return filter_var($string, FILTER_VALIDATE_BOOLEAN);
}
Dmitry
  • 1,085
  • 2
  • 11
  • 19
2

The answer by @GordonM is good. But it would fail if the $string is already true (ie, the string isn't a string but boolean TRUE)...which seems illogical.

Extending his answer, I'd use:

$test_mode_mail = ($string === 'true' OR $string === true));
Ema4rl
  • 577
  • 1
  • 6
  • 17
2

I do it in a way that will cast any case insensitive version of the string "false" to the boolean FALSE, but will behave using the normal php casting rules for all other strings. I think this is the best way to prevent unexpected behavior.

$test_var = 'False';
$test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
$result = (boolean) $test_var;

Or as a function:

function safeBool($test_var){
    $test_var = strtolower(trim($test_var)) == 'false' ? FALSE : $test_var;
    return (boolean) $test_var;
}
Syntax Error
  • 4,475
  • 2
  • 22
  • 33
0

You can use the settype method too!

$string = 'false';
$boolean = settype($string,"boolean");
var_dump($boolean); //see 0 or 1
David Kooijman
  • 632
  • 3
  • 18
Nai
  • 430
  • 5
  • 15
  • 1
    This is invalid PHP code. The correct case for these terms should be `echo` and `settype()`. PHP also requires semicolons at the end of every line. I don't know how this got 2 upvotes, and was also edited by someone who didn't know these absolute basics of PHP that you learn on day 1. – BadHorsie Nov 11 '21 at 09:01
0

I was getting confused with wordpress shortcode attributes, I decided to write a custom function to handle all possibilities. maybe it's useful for someone:

function stringToBool($str){
    if($str === 'true' || $str === 'TRUE' || $str === 'True' || $str === 'on' || $str === 'On' || $str === 'ON'){
        $str = true;
    }else{
        $str = false;
    }
    return $str;
}
stringToBool($atts['onOrNot']);
tomi
  • 9
  • 2
  • 1
    i was looking for help in the first place, but did not find anything as easy as as i hoped. that's why i wrote my own function. feel free to use it. – tomi Apr 05 '16 at 18:02
  • Perhaps lower the string to you don't need all the or conditions `$str = strtolower($str); return ($str == 'true' || $str == 'on');` – Cyclonecode Sep 28 '20 at 22:44
0
$string = 'false';

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

var_dump($test_mode_mail);

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

You have to do it manually

penny
  • 13
  • 3
-1

Edited to show a working solution using preg_match(); to return boolean true or false based on a string containing true. This may be heavy in comparison to other answers but can easily be adjusted to fit any string to boolean need.

$test_mode_mail = 'false';      
$test_mode_mail = 'true'; 
$test_mode_mail = 'true is not just a perception.';

$test_mode_mail = gettype($test_mode_mail) !== 'boolean' ? (preg_match("/true/i", $test_mode_mail) === 1 ? true:false):$test_mode_mail;

echo ($test_mode_mail === true ? 'true':'false')." ".gettype($test_mode_mail)." ".$test_mode_mail."<br>"; 
JSG
  • 390
  • 1
  • 4
  • 13
-1

A simple way is to check against an array of values that you consider true.

$wannabebool = "false";
$isTrue = ["true",1,"yes","ok","wahr"];
$bool = in_array(strtolower($wannabebool),$isTrue);
Tajin
  • 1
-4

You should be able to cast to a boolean using (bool) but I'm not sure without checking whether this works on the strings "true" and "false".

This might be worth a pop though

$myBool = (bool)"False"; 

if ($myBool) {
    //do something
}

It is worth knowing that the following will evaluate to the boolean False when put inside

if()
  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Everytyhing else will evaluate to true.

As descried here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89