(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();
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.