[php] 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.

This question is related to php string casting boolean

The answer is


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.


You can use settype method too!

SetType($var,"Boolean") Echo $var //see 0 or 1


Edited to show a possibility not mentioned here, because my original answer was far from related to the OP's question.

preg_match(); Is possible to use. However, in most applications it will be much more heavy to use than other answers here.

if (preg_match("/true/i", "true PHP is a web scripting language of choice.")) {
    echo "<br><br>Returned true";
} else {
    echo "<br><br>Returned False";
}

/(?:true)|(?:1)/i Can also be used if needed in certain situations. It will not return correctly when it evaluates a string containing both "false" and "1".


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

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.


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.)


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;
}

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.


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

(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

you can use json_decode to decode that boolean

$string = 'false';
$boolean = json_decode($string);
if($boolean) {
  // Do something
} else {
  //Do something else
}

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


function stringToBool($string){
    return ( mb_strtoupper( trim( $string)) === mb_strtoupper ("true")) ? TRUE : FALSE;
}

or

function stringToBool($string) {
    return filter_var($string, FILTER_VALIDATE_BOOLEAN);
}

You can use boolval($strValue)

Examples:

<?php
echo '0:        '.(boolval(0) ? 'true' : 'false')."\n";
echo '42:       '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0:      '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2:      '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"":       '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0":      '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1":      '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]:   '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]:       '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>

Documentation http://php.net/manual/es/function.boolval.php


In PHP you simply can convert a value to a boolean by using double not operator (!!):

var_dump(!! true);     // true
var_dump(!! "Hello");  // true
var_dump(!! 1);        // true
var_dump(!! [1, 2]);   // true
var_dump(!! false);    // false
var_dump(!! null);     // false
var_dump(!! []);       // false
var_dump(!! 0);        // false
var_dump(!! '');       // false


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

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

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

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.


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.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas