Managing Variables
Three language constructs are used to manage variables. They enable you to check if certain variables exist, remove variables, and check variables' truth values.
1.isset()
isset() determines whether a certain variable has already been declared by PHP. It returns a boolean value true if the variable has already been set, and false otherwise, or if the variable is set to the value NULL. Consider the following script:
if (isset($first_name)) {
print '$first_name is set';
}
This code snippet checks whether the variable $first_name is defined. If $first_name is defined, isset() returns true, which will display '$first_name is set.' If it isn't, no output is generated.
isset() can also be used on array elements (discussed in a later section) and object properties. Here are examples for the relevant syntax, which you can refer to later:
Checking an array element:
if (isset($arr["offset"])) {
...
}
Checking an object property:
if (isset($obj->property)) {
...
}
Note that in both examples, we didn't check if $arr or $obj are set (before we checked the offset or property, respectively). The isset() construct returns false automatically if they are not set.
isset() is the only one of the three language constructs that accepts an arbitrary amount of parameters. Its accurate prototype is as follows:
isset($var1, $var2, $var3, ...);
It only returns TRue if all the variables have been defined; otherwise, it returns false. This is useful when you want to check if the required input variables for your script have really been sent by the client, saving you a series of single isset() checks.
2. 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().
3.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
No comments:
Post a Comment