https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
http://www.zomeoff.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/
- This will check to see if there is a value for an item in an array.
- This will return
true
if the value is set to''
. - This will return
false
if the value is set tonull
.
$people = array(
'one' => 'Eric',
'two' => '',
'three' => null,
'four' => 0,
'five' => '0',
'six' => ' ',
);
if ( isset( $people['one'] ) ) {}; // true
if ( isset( $people['two'] ) ) {}; // true
if ( isset( $people['three'] ) ) {}; // false
if ( isset( $people['four'] ) ) {}; // true
if ( isset( $people['five'] ) ) {}; // true
if ( isset( $people['six'] ) ) {}; // true
Only returns false if the value is set to null
.
- Will return
true
if set to''
, ornull
- These are values empty will evaluate as empty.
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
- null
- false
- array() (an empty array)
- var $var; (a variable declared, but without a value in a class)
$people = array(
'one' => 'Eric',
'two' => '',
'three' => null,
'four' => 0,
'five' => '0',
'six' => ' ',
);
if ( empty( $people['one'] ) ) {}; // false
if ( empty( $people['two'] ) ) {}; // true
if ( empty( $people['three'] ) ) {}; // true
if ( empty( $people['four'] ) ) {}; // true
if ( empty( $people['five'] ) ) {}; // true
if ( empty( $people['six'] ) ) {}; // false
So the big difference here is that empty
will also return true if the value is ''
. This
makes it the more safe function to use if you want to make sure ''
isn't accepted.
$people = array(
'one' => 'Eric',
'two' => '',
'three' => null,
'four' => 0,
'five' => '0',
'six' => ' ',
);
if ( $people['one'] ) {}; // true
if ( $people['two'] ) {}; // false
if ( $people['three'] ) {}; // false
if ( $people['four'] ) {}; // false
if ( $people['five'] ) {}; // false
if ( $people['six'] ) {}; // true
isset
checks if something exists, so you can check isset( $something['key'] )
, where as empty
checks if it is empty. empty( $something['key'] )
would throw an error if $something['key']
wasn't set/didn't exists. You can use if ( $var )
over if ( ! empty( $var ) )
.
Adding in comments from @bradp