1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

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

Discussion in 'XenForo Development Discussions' started by Jaxel, Dec 2, 2010.

  1. Jaxel

    Jaxel Well-Known Member

    Lets say I have an array:
    $array = array(
        '1' => true,
        '2' => '1',
        '3' => false,
        '4' => '0',
        '5' => null
    Simple right? Now lets say I'm returning using the following:
    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...
    return isset($array[$key]) && $array[$key] ? true : false;
    Is this by design? And why?
  2. Mike

    Mike XenForo Developer Staff Member

    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
  3. ragtek

    ragtek Guest

  4. Jaxel

    Jaxel Well-Known Member

    Okay... what if I wanted to do something like:
    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.
  5. Mike

    Mike XenForo Developer Staff Member

    For a situation like that, yes you have to use isset().
  6. Kier

    Kier XenForo Developer Staff Member

    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 :)
    Darkimmortal likes this.

Share This Page