0

After all this time I have been checking on a variable with both isset() && ! empty() function as following.

if ( isset($my_arr['myh_index']) && ! empty($my_arr['myh_index']) ) { ... }

Because I though I have read somewhere that isset() function only checks if a variable is set, it will also return true even a variable contains null or an empty string. That's why I also check with !empty() function to make sure.

Today, I found out that the difference is that !empty() function does not generate any warning or notice message.

Can I just only check with if ( ! empty($my_arr['my_index']) ) { ... } to prevent

  • 'Notice (8): Undefined variable'
  • 'Warning (2): Illegal string offset'
  • 'Notice (8): Undefined index'

?

JJJ
  • 32,902
  • 20
  • 89
  • 102
O Connor
  • 4,236
  • 15
  • 50
  • 91
  • 7
    They're not the same, and have never been the same, not even in PHP7. – Jonnix Feb 07 '19 at 10:33
  • https://stackoverflow.com/questions/20582962/whats-the-difference-between-isset-and-empty-in-php – mujuonly Feb 07 '19 at 10:33
  • There is an answer to the difference between isset() and empty(). https://stackoverflow.com/questions/20582962/whats-the-difference-between-isset-and-empty-in-php. And far as i know there were no changes in PHP 7. – Malte Kölle Feb 07 '19 at 10:35
  • https://3v4l.org/qVCnV see there – Eakethet Feb 07 '19 at 10:36
  • See [this](http://sandbox.onlinephpfunctions.com/code/99d5ebe0b55945f751b960b31f4ea5a1eebd6246) – Cid Feb 07 '19 at 10:39
  • `""`, `0` and `false` are set, but empty – Cid Feb 07 '19 at 10:40
  • I just edited my question because it was duplicated. – O Connor Feb 07 '19 at 10:47
  • `if (!empty($my_arr['my_index']))` will return `true` (not empty) if `empty($my_arr['my_index'])` is set **and** doesn't contain any of those : `0`, `false`, `""`, `"0"`, `array()` or `[]` (empty array) – Cid Feb 07 '19 at 10:52
  • For more information, [Read That Fine Manual](http://php.net/manual/en/function.empty.php) (especially the *return values* part) – Cid Feb 07 '19 at 10:53
  • I do understand about the return value the `empty()` function returns. But I just want to ask if `! empty()` function can surely prevent the warning and notice message mentioned in my question above. Because all this time I though `empty()` function did not prevent such message. That's why I have been using both `if( isset() && !empty() )` which seems not to be necessary. – O Connor Feb 08 '19 at 08:51

0 Answers0