Oto Shavadze
Oto Shavadze

Reputation: 42853

Why is "undefined + x = x" in php?

If we have this code

echo $a + 1;

php returns: Notice: Undefined variable: a in... and also 1

This is little unclear situation right? if $a is undefined (and $a is really undefined), why is undefined + 1 = 1 ? result mus be also undefined right? interesting to hear your opinion.

Upvotes: 1

Views: 85

Answers (2)

middelpat
middelpat

Reputation: 2585

$a + 1 gives php the assumtion $a is of type int. the default value of int cannot be undefined and is 0. then 0 + 1 = 1

Upvotes: 2

deceze
deceze

Reputation: 522510

The default value for a non-existent variable is null. null cast to a number is 0. 0 + a number is this number.

Upvotes: 4

Related Questions