Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Enhancing a Simple PHP Application Adding Search: Controller & View Accounting for Empty Results

Dayne Wright
Dayne Wright
11,235 Points

Using isset vs. !empty?

I think I have a good idea of the differences between these two, but I am curious why you could not use isset() in place of !empty() here? Is there a reason why one is preferred over the other?

I could be missing something, but it seems they would accomplish the same thing, right?

index.php
<?php

    $recommendations = array();

?><html>
<body>

    <h1>Flavor Recommendations</h1>
<?php
if (!empty($recommendations)) { ?>
    <ul>
        <?php foreach($recommendations as $flavor) { ?>
            <li><?php echo $flavor; ?></li>
        <?php } ?>
    </ul> <?php
} ?>         

</body>
</html>

1 Answer

They're different, and the differences are they reveal the distinction between empty and null variables.

Null variables exits in the following three cases only.
(1): The variable has not been set to any value.
(2): The variable has been unset();
(3): The variable has been assigned the constant value NULL.

isset(); is a function that returns boolean true if a variable is not null. The opposite of isset(); is is_null(); In other words, it returns true only when the variable is null. The only difference is that isset() can be applied to unknown variables, but is_null() only to declared variables.

By comparison, empty(); is a function that tests whether or not a variable is empty.

A variable is empty when it does not exist or returns the boolean value false. Empty variables exist in the following instances:

  1. Empty strings
  2. Boolean false
  3. Unset array()
  4. Variable assigned NULL
  5. Variable assigned 0
  6. Unset variables

In the case of an empty array like $recommendations, !empty would return boolean false, but isset() would return a boolean true, because the value is empty but not null.

This distinction is a little confusing, but there is a really handy explanation and table about the results of these three functions at https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/.

Hope this helps.