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

Using array_key_exists to avoid undefined index

A better way to write the conditional is to include the array_key_exists, which takes two parameters, the key and the array.
Categories:
  1. gears_of_existence.jpg

    An array contains a series of information. Retrieving a single piece of information involves iterating over a loop, such as foreach or calling the index directly using the array name and the index. For example,

    PHP:
    1. $this->options['use_thread_system']
    In several places, I use information in the array to determine whether to load something else. For example, if the thread system is enabled then do something.

    PHP:
    1. if ( $this->options['use_thread_system'] == true )
    The challenge in the above code is first looking for the existence of the 'use_thread_system' index. If it doesn't exist then PHP returns a notice. The program now has a bug, as well as unexpected results.

    A better way to write the conditional is to include the array_key_exists, which takes two parameters, the key and the array.

    PHP:
    1. if ( array_key_exists( 'use_thread_system', $this->options ) && $this->options['use_thread_system'] == true )
    2.  
    This code stops the undefined index notice and makes sure the conditional is run only when the thread system is enabled.
    robru likes this.

Comments

To make a comment simply sign up and become a member!
  1. doublespaces
    Thank you for your updates to XF 2.0. I'm watching closely and will attempt to make a transition for a new forum when you hit beta.
    1. LPH
      The last few days have been spent making the XF1 portion of the bridge solid. I believe this was achieved about 1/2 hour ago with a few line changes in the dashboard widget.
      doublespaces likes this.