Why does an echo expression with undefined variables print 0?

I found this strange behavior:

$a = $b + $c;
echo $a; //prints 0

prints 0 while this is:

$a = $b;
echo $a; //doesn't print anything  

doesn't print anything.
Is this explained in a meaningful way?

+4
source share
3 answers

In the same context ( $a = $b + $c), they are converted into the number of the operator +, and the same applies to all the mathematical operators: +, *, -, /.

In another, it is just an empty variable (undefined variables are set to NULL), which are forced to a string using echo.

See http://php.net/manual/en/language.types.type-juggling.php

echo "Cast to int becomes: " . (integer) NULL; // 0

echo "Cast to string becomes" . (string) NULL; // (Empty string) 
+2
source

. Undefined $b $c null. PHP $a = null + null $a = (int) null + (int) null, $a = 0 + 0. $a 0.

, $a = $b $a = null, , echo $a, .

, - http://php.net/manual/en/language.types.type-juggling.php

+3

Type of casting. PHP tries to guess the most appropriate type of variable in context and translates the values ​​accordingly.

<?php

$a = null;
$b = null;
var_dump($a . $b); // string(0) ""
var_dump($a + $b); // 0
var_dump($a / $b); // float(NAN), also warns about Division by zero
var_dump($a - $b); // 0
var_dump($a * $b); // 0

This can also be done:

echo "8 beers" + 5; // 13
0
source

Source: https://habr.com/ru/post/1626399/


All Articles