• Welcome to Tux Reports: Where Penguins Fly. We hope you find the topics varied, interesting, and worthy of your time. Please become a member and join in the discussions.

Using array_key_exists to avoid undefined index

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:
$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:
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:
if ( array_key_exists( 'use_thread_system', $this->options ) && $this->options['use_thread_system'] == true )

This code stops the undefined index notice and makes sure the conditional is run only when the thread system is enabled.
  • Like
Reactions: robru

Blog entry information

Author
LPH
Views
6,497
Comments
2
Last update

More entries in Technology

More entries from LPH

Top