Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
Run Avatar asked Sep 07 '11 15:09

Run


People also ask

How parse boolean in PHP?

Use filter_var() function to convert string to boolean value. Approach using PHP filter_var() Function: The filter_var() function is used to filter a variable with specified filter. This function is used to both validate and sanitize the data.

How do you cast a variable to a boolean?

Converting to boolean ¶ To explicitly convert a value to bool, 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 bool argument. See also Type Juggling.

Is there boolean in PHP?

PHP uses the bool type to represent boolean values. To represent boolean literals, you can use the true and false keywords. These keywords are case-insensitive.

Is 1 true in PHP?

The boolean values are called true and false in php. In the case of true , the output is 1 . While with the false , it does not show any output. It is worth noting that the browser always renders these values in strings.


1 Answers

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 
like image 121
Brad Avatar answered Sep 26 '22 00:09

Brad