1

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.

EnglishAdam
  • 1,380
  • 1
  • 19
  • 42
  • 2
    I had to think about this one! The internal type, as recorded by PHP, will be Boolean, but it is cast to an integer when you echo it, or if you perform a maths operation on it. – halfer Oct 02 '13 at 17:53
  • Thanks, so it is recast if multiply by a boolean! oh.... – EnglishAdam Oct 02 '13 at 18:04

4 Answers4

3

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.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
2

true is not numeric, but when it's converted to a string for concatenation, it is converted to "1". Similarly, false is converted to the empty string "".

If you were to do:

$a_string = "$a";

Then is_numeric($a_string) would be true, because the value of $a_string would be "1". Using a boolean in a context that requires a string converts the value to either "1" or "".

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

The value false is not a constant for the number 0, it is a boolean value that indicates false. The value true is also not a constant for 1, it is a special boolean value that indicates true. It just happens to cast to integer 1 when you print it or use it in an expression, but it's not the same as a constant for the integer value 1 and you shouldn't use it as one. But there may be times when it might be helpful to see the value of the Boolean as a 1 or 0. Here's how to do it.

<?php 
 $var1 = TRUE; 
 $var2 = FALSE; 

  echo $var1; // Will display the number 1 

  echo $var2; //Will display nothing 

  /* To get it to display the number 0 for 
  a false value you have to typecast it: */ 

  echo (int)$var2; //This will display the number 0 for false. 

 var_dump($var1); //bool(true)

 var_dump($var2); //bool(false) 

 ?>

References:

Bool

var_dump

Emilio Gort
  • 3,475
  • 3
  • 29
  • 44
1

$a is not considered 1. It's represented as the string "1" when echoed.

federico-t
  • 12,014
  • 19
  • 67
  • 111
  • Thanks, so it is never a string though? – EnglishAdam Oct 02 '13 at 17:58
  • @Gamemorize No. You need to understand that PHP hwill often convert values from one type to another as needed by context. But the original types are still distinct. – Barmar Oct 02 '13 at 18:02