Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized variables in PHP

The PHP manual says:

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

I was playing around with uninitialized variables for golfing, but the program didn't do what I expected it to do. Upon examination, I noticed this weird behavior (all used variables are uninitialized):

php > $a = $a + 1;
PHP Notice:  Undefined variable: a in php shell code on line 1
php > $b = $b - 1;
PHP Notice:  Undefined variable: b in php shell code on line 1
php > $c++;
PHP Notice:  Undefined variable: c in php shell code on line 1
php > $d--;
PHP Notice:  Undefined variable: d in php shell code on line 1
php > var_dump($a);
int(1)
php > var_dump($b);
int(-1)
php > var_dump($c);
int(1)
php > var_dump($d);
NULL

+ 1, - 1, and ++ work as described in the manual. However, -- doesn't.

$a, $b, and $c can be used for counting, afterwards. But $d--;, won't change $d's value because $d is NULL.

Why is $d set to NULL, not to -1?

Using prefix operators yields the same results, by the way: The variable is set to 1 for ++$v; but to NULL for --$v;.

like image 925
UTF-8 Avatar asked Dec 24 '16 11:12

UTF-8


1 Answers

From the manual:

Note: …Decrementing NULL values has no effect too, but incrementing them results in 1.

So, an unitialized variable gets a NULL value. Incrementing this value gets the 1 (as NULL + 1). But an attempt to decrementing it doesn't have any effect as described in the documentation.

Also, there is a very good explanation in the relevant topic.

It may seem counterintuitive, but it is a consequence of the typing model of the language. So, to avoid this behavior, just always follow the good practices: always initialize a variables and beware of arithmetic operations on the non-numeric values.

like image 108
Timurib Avatar answered Oct 04 '22 00:10

Timurib