Programming Tutorials

unset() and empty() functions in PHP

By: Emiley J. in PHP Tutorials on 2008-11-21  

unset()

unset() "undeclares" a previously set variable, and frees any memory that was used by it if no other variable references its value. A call to isset() on a variable that has been unset() returns false.

For example:

$name = "John Doe";
unset($name);
if (isset($name)) {
print "$name is set';
}

This example will not generate any output, because isset() returns false. unset() can also be used on array elements and object properties similar to isset().

empty()

empty() may be used to check if a variable has not been declared or its value is false. This language construct is usually used to check if a form variable has not been sent or does not contain data. When checking a variable's truth value, its value is first converted to a Boolean according to the rules in the following section, and then it is checked for true/false.

For example:

if (empty($name)) {
print 'Error: Forgot to specify a value for $name';
}

This code prints an error message if $name doesn't contain a value that evaluates to true.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)