OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Boolean In PHP

Code snippet for how to Convert Variable From String To Boolean In PHP with sample and detail explanation

In most coding scenarios, there often comes a need to convert a variable from one type to another for various data manipulation purposes. This article takes us through a simple demonstration of how to convert a variable from string to boolean in PHP.

Code snippet Example

Let’s take a look at an example code snippet to start:

<?php
$strVar = "true";
$boolVar = filter_var($strVar , FILTER_VALIDATE_BOOLEAN);
var_dump($boolVar);
?>

Code Explanation for Example

The provided code snippet is a straightforward PHP block that demonstrates how to convert a variable from string to boolean. Let’s break it down further:

  1. The first line within the PHP block <?php assigns a string value "true" to the variable $strVar.

  2. In the next line, we are using filter_var() function. This is a built-in PHP function for filtering and sanitizing data. Here, it is being used to convert the string variable $strVar to boolean.

    • FILTER_VALIDATE_BOOLEAN validates a boolean, returns TRUE for “1”, “true”, “on” and “yes”, and FALSE otherwise.
  3. Finally, var_dump($boolVar); function is used to display structured information(type and value) about $boolVar, which will now hold a boolean value. If the string value represented ‘true’, $boolVar will now hold true (bool), if ‘false’ it will hold false.

Remember that PHP is a loosely typed language so this kind of type juggling is allowed and even common in some coding scenarios. Using these tools properly allows for more flexibility and control over your data and how you manipulate it.

php