如果我尝试获取未定义变量的大小会发生什么? (PHP)

如果我尝试获取未定义变量的大小会发生什么?  (PHP)

问题描述:

(PHP) What happen if I try to get an undefined variable size with sizeof method?

Like:

<?
print_r(sizeof($undefined_variable));

Can I do this? What's the value?

In my playground always run into error, but when i try this code:

<?
print_r(sizeof($undefined_variable));
exit();

Size of an undefined variable picture

I'm so curious after error why I get back a zero value. Sorry for my bad English

sizeof is an exact alias of count. count() can only return the number of items in an object if the object interfaces with the Countable interface which an undefined variable does not which is causing the error.

However the reason for the 0 being output is that print_r outputs a 0 anytime an error has occured.

for example try:

print_r(4 + hello);

It still outputs a 0. The error was non fatal so the program continues to execute.

To answer your second question, if you try the following code:

for ($i=0; $i<sizeof($undefined_variable); $i++) {
    echo $i;
}

echo "Hi";

Only 'Hi' will get output. The error aborts the whole for loop.

sizeof() is an array funciton returns the size of the array, so you will get php warning about variable( not decalred) and also a 0 as result.

From the manual for the function - count():

Caution count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.

sizeof is an alias of count.

See: http://php.net/manual/en/function.count.php

Hence:

<?php
print_r(sizeof($undefined_variable));

Will output:

0

As sizeof($undefined_variable) evaluates to 0, and print_r(0) results in 0.