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.

有帮助吗?

解决方案

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.

其他提示

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 "".

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top