Skip to content

Instantly share code, notes, and snippets.

@gregrickaby
Forked from efuller/array.md
Last active May 4, 2020 19:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gregrickaby/45071cf2a292abf07fd351b1df617005 to your computer and use it in GitHub Desktop.
Save gregrickaby/45071cf2a292abf07fd351b1df617005 to your computer and use it in GitHub Desktop.
PHP Array isset and empty

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/

Checking a value directly

$people = array(
	'one'   => 'Eric',  // true
	'two'   => '',      // false
	'three' => null,    // false
	'four'  => 0,       // false
	'five'  => '0',     // false
	'six'   => ' ',     // true
);

if ( $people['one'] ) {};

isset

  • 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 to null.
$people = array(
	'one'   => 'Eric',  // true
	'two'   => '',      // true
	'three' => null,    // false
	'four'  => 0,       // true
	'five'  => '0',     // true
	'six'   => ' ',     // true
);

if ( isset( $people['one'] ) ) {};

Only returns false if the value is set to null.

empty

  • Will return true if set to '', or null
  • 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', // false
	'two'   => '',     // true
	'three' => null,   // true
	'four'  => 0,      // true
	'five'  => '0',    // true
	'six'   => ' ',    // false
);

if ( empty( $people['one'] ) ) {};

Takeaways

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment