Re: No notices for undefined index

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, 2010-04-08 at 15:22 -0500, Shawn McKenzie wrote:

> Shawn McKenzie wrote:
> > Bob McConnell wrote:
> >> In the first case, $a=5 creates a multi-typed variable. The interpreter
> >> makes its best guess how the next two expressions should be interpreted.
> >> In both cases, they look a lot like an index into a character array
> >> (string), and 'test' evaluates numerically to zero. Both are valid
> >> offsets for a string, so no messages are generated.
> >>
> >> In the second case, $a is explicitly declared as an array. This give the
> >> interpreter a lot more detail to work from. The two expressions are now
> >> an index and a key for the array. But both of them evaluate to offsets
> >> that have not been assigned, which raises a flag and creates the
> >> warnings.
> >>
> >> Such are the joys of loosely typed languages.
> >>
> >> Bob McConnell
> > 
> > Yes, this is what I was thinking as well, however:
> > 
> > $a=5;
> > print $a[0];   // if it is index 0 then it should print 5 yes?
> > print $a[100]; // there is no index 100 so why no notice?
> > 
> 
> $a='5';
> print $a[0];   // prints 5
> print $a[100]; // Notice: Uninitialized string offset:  100
> 
> So it seems, in the first case with the integer 5 that the interpreter
> is saying:
> 
> - Since $a is not an array I'll treat $a[0] and $a[100] as a string
> offset, but since $a is not a string I won't do anything.
> 
> Just seems stupid IMHO.
> 
> -- 
> Thanks!
> -Shawn
> http://www.spidean.com
> 


I think it just returns null if the offset goes beyond the length of the
string. In C and C++ doing something like this would take you beyond
that variables memory allocation into neighbouring variables. I believe
PHP is trying to prevent problems where that might occur by returning
null instead.

This is only conjecture as I don't know exactly what happens, and I
can't find anything in the manual that explains what should happen when
you treat a string like an array in PHP. However, throwing some sort of
error or notice would be nice, but could be worked around by checking
the array type and length (the count() function returns the string
length I believe as well as the array size) as it does seem that PHP is
treating a string like a special sort of array.

Thanks,
Ash
http://www.ashleysheridan.co.uk



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux