Search code examples
phparraysarray-key-exists

What is the proper way of checking a table key existence before using its value?


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)) { ... }

Solution

  • 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.