Search code examples
phpbooleanisnumeric

PHP: Why is True a Number but not Numeric?


So I'm trying to understand WHY this occurs:

<?php
$a = TRUE;          
$b = FALSE;

echo "a is ".$a."<br/>";
if (is_numeric($a)){
echo "a is numeric<br/>";
}
echo "b is ".$b."<br/>";
if (is_numeric($b)){
echo "b is numeric<br/>";
}   

?>

gives the following output

a is 1

b is

So A is considered to be 1 but not considered to be numeric.

The manual says that a string like "42" is considerd numeric.


Solution

  • It is not considered numeric. It is auto-converted to 1 when you echo it. This is called type juggling and it means stuff like this is actually legal in PHP:

    php > $a = true;
    php > $b = $a + 5;
    php > echo $b;
    6
    
    php > $c = "hello ".$a;
    php > echo $c;
    hello 1
    

    You can use is_bool to find out it is actually boolean.