Why can't XenForo handle non-existent array indexes?

Jaxel

Well-known member
Lets say I have an array:
Code:
$array = array(
    '1' => true,
    '2' => '1',
    '3' => false,
    '4' => '0',
    '5' => null
)
Simple right? Now lets say I'm returning using the following:
Code:
return $array[$key] ? true : false;
Also simple, if the keyed value is true, return true, else false. So for keys 1 and 2, it returns true, and for keys 3, 4 and 5, it returns false. However, here comes in the issue... what happens at key 6? In most other systems I have worked with, a non-existent key returns a defaulted false. Since key 6 doesn't exist, its defined as null.

But in XenForo, it doesn't work the same way. Instead the program will come to a screeching halt and loudly fail with an error about non-existent indexes. Because of this, it forces me to include extra checks for pretty much EVERY instance I use an array...
Code:
return isset($array[$key]) && $array[$key] ? true : false;

Is this by design? And why?
 
This isn't XenForo. It's PHP when you have notices on. Programming without notices is bad form and a trivial way to introduce bugs. If you make a typo and you suppress notices, you won't get an error, so the logic needs to fall over.

And you don't need an extra check. Just use empty(): !empty($x) is the same as isset($x) && $x
 
Okay... what if I wanted to do something like:
Code:
if (isset($array[$key]) && $array[$key] == "string") { }

Is there some sort of shortcut I can use like !empty?

I've switched all instances in my code to !empty... looking at resources on the net, I can see that empty is very slightly faster than isset.
 
looking at resources on the net, I can see that empty is very slightly faster than isset.
It is, but it's a micro-optimisation. The time you would spend swapping all your isset() instances to empty() would probably exceed the total amount of processing time saved by doing so for every instance in the world ever. Micro-optimisations are rarely worth the effort :)
 
Top Bottom