Sorry if it’s an irritating question (i come from a ruby background and i am new to PHP).
I find it kind of weird that you can’t do:
if($defined_array['undefined_index'] == 'a string') {
do_something();
}
without getting slammed in the face with a warning.
- In this particular case, if the variable doesn’t exist, how come you get a warning ? This is a weird implementation of equality for a loosely-typed language. It would make much more sense to only get a
false. Is it due to interpreter limitations ? What are the technical reasons that are behind this ? I’m just curious. -
Is there any function, construct, idiom or whatever that i don’t know that would avoid me to do this every 4 lines or so:
if(isset($defined_array['undefined_index']) && $defined_array['undefined_index'] == 'a string') { do_something(); }I know that i could declare every single array keys i intend to use, but what’s the point of not being forced into declaring variables before using them if PHP intends to slap you every time you do it ?
The reason for the warning is for code safety reasons. While it’s possible that the reason the array key doesn’t exist is because it’s not supplied in this instance, it’s also possible that there was a typo in either setting or retrieving the element. Without warnings, such coding errors would be harder to notice.