3

I want to check if $table['key'] exists before using it. What is the proper way of doing this?

I've seen a lot of different codes, but I do not know if they are all equivalent and right. Here are a few examples :

// 1
if(isset($table['key'])) { ... }

// 2
if(isset($table) and isset($table['key'])) { ... }

// 3
if(isset($table) and array_key_exists('key',$table)) { ... }
Silverspur
  • 891
  • 1
  • 12
  • 33

2 Answers2

2
if (isset($table['key']))

Yes.

if (isset($table) and isset($table['key']))

That's redundant, there's no advantage to checking both individually.

if (isset($table) and array_key_exists('key', $table))

Yes, this is also a good method if $table['key'] may hold a null value and you're still interested in it. isset($table['key']) will return false if the value is null, even if it exists. You can distinguish between those two cases using array_key_exists.

Having said that, isset($table) is not something you should ever be doing, since you should be in control of declaring $table beforehand. In other words, it's inconceivable that $table may not exist except in error, so you shouldn't be checking for its existence. Just if (array_key_exists('key', $table)) should be enough.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • One thing to note is that `isset()` is a language construct and `array_key_exists()` is a function call, if used many times it makes a difference :) also, `isset()` works on objects that implement `ArrayAccess`. – Ja͢ck Jul 08 '14 at 22:21
1

The rule of thumb I personally apply:

  1. If the value that corresponds with the key may be null:
    1. If $table may not exist, use isset($table) && array_key_exists('key', $table).
    2. Otherwise, use array_key_exists('key', $table).
  2. In all other cases, use isset($table['key']).

In the cases of 1.1 and 1.2, it's technically possible that $table is not an array; in that case you would need to add is_array($table) as well ... but if it ever gets this far, something else is wrong imho.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309