Ferex
Ferex

Reputation: 575

Why echoing an expression with unset variables prints 0?

I found this strange behaviour:

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

prints 0 while this:

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

doesn't print anything.
Is it explainable in a meaningful way?

Upvotes: 4

Views: 85

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92304

In one context ($a = $b + $c), they are being converted into numbers because of the + operator and the same would apply with all mathematical operators: +, *, -, /.

In the other, it's just an empty variable (undefined variables are set to NULL) being coerced into a string by the 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) 

Upvotes: 2

k0pernikus
k0pernikus

Reputation: 66717

Type casting. PHP tries to guess to most fitting variable type on context and casts 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

It's also why you can do:

echo "8 beers" + 5; // 13

Upvotes: 0

Scott
Scott

Reputation: 12376

This is a side effect of type juggling. Undefined variables $b and $c are equivalent to null. In PHP, $a = null + null is equivalent to $a = (int) null + (int) null which is the same as $a = 0 + 0. This is the reason that $a equals 0.

It follows that $a = $b is the same as $a = null, so when you echo $a, nothing is printed.

This is a decent reference that explains type juggling - http://php.net/manual/en/language.types.type-juggling.php

Upvotes: 3

Related Questions