Monday 2 February 2015

PHP Using isset vs. !empty?

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?

<?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>

 

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.

 


0 comments:

Post a Comment