Skip to content

All topics  /  PHP

How to Check If String is Boolean in PHP?

PHP ·

Hi Dev,

Now, let's see example of How to check if string is boolean in PHP. This post will give you simple example of PHP is_bool() function example. We will use PHP if boolean check with code examples. you can see PHP in check string is boolean or not. So, let's follow few step to create example of PHP boolean Code Example.

Example 1:


index.php

<?php
    $x = false;
    $y = 0;
    // Since $x is a boolean, it will return true
    if (is_bool($x) === true) {
        echo "Yes, this is a boolean";
    }
    // Since $y is not a boolean, it will return false
    if (is_bool($y) === false) {
        echo "\n No, this is not a boolean";
    }
?>

Output:

Yes, this is a boolean
No, this is not a boolean

Example 2:

index.php

<?php
    $values = array(false, true, null, 'abc', '23', 23.5, ' ', 0);
    foreach ($values as $value) {
        echo " <br> is_string(";
        var_export($value);
        echo ") = ";
        echo var_dump(is_string($value));
    }
?>

Output:

is_string(false) = bool(false)
is_string(true) = bool(false)
is_string(NULL) = bool(false)
is_string('abc') = bool(true)
is_string('23') = bool(true)
is_string(23.5) = bool(false)
is_string(' ') = bool(true)
is_string(0) = bool(false)

I hope it could help you...