SUBSCRIBE VIA RSS


Subscribe to our feed

Symfony Experts

Symfony Experts
If you have an urgent question for a symfony-related issue, this is the place to ask.

Topics

Stack Overflow


The old fashioned way

RECENT TUNES

July 11, 2009 – 2:52am php isset and not empty

I find myself doing this a lot:

if (isset($myarray['foo']) && $myarray['foo'])) {
  // do something
}

But I thought there had to be a better way, and one that would not throw undefined errors. A quick google search came up with a few good hits, include the PHP manual page for empty().

The manual says that when using empty(), no warnings are thrown when a variable is not set. It will return true in the following cases:

“” (an empty string)
0 (0 as an integer)
“0” (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)

Keep in mind that an object with no properties is not considered empty().

Now, we can make our code a bit more beautiful:

if (!empty($myarray['foo'])) {
  // do something
}

I’ve known about empty() for a long time, but for some reason always seemed to choose isset() over empty(), even in cases like this.

Posted by in  Uncategorized   |  

3 Responses to php isset and not empty

  1. Harry Walter says:

    Bear in mind that you often can’t use empty on the response from and object method unline isset.

    For example in symfony if you had a blog object you can do:

    if(isset($blog->getTitle()) && $blog->getTitle() != “”){}

    But you cannot do if(empty($blog->getTitle())){}

  2. Jon Williams says:

    And then there’s array_key_exists() sigh…

  3. Andrew Noyes says:

    To expand upon what Harry Walter said, empty() can’t be used on the value returned by any function, be it an object method or a regular function. empty() has some funky behavior because it’s part of the PHP interpreter and is a language component rather than a function, just like echo.