Working With PHP Data Types - If this, if that
(Page 4 of 5 )
PHP's if statements can be used to check the validity of a variable, its integrity, or even the presence of data within a variable. Let's use PHP’s gettype function in our first example to check the data type of a variable:
<?
$i = 10;
if(gettype($i) == "integer") // Checks if variable i is an integer
{
echo("the variable $i is an integer"); // If integer, then display
} else {
echo("variable $i is not an integer"); // If not integer, then display
}
?>Because we have given the $i variable a default value of ten, it is seen as an integer and the text "the variable $i is an integer" will be displayed using the echo function. Try changing 10 to 10.1. Because 10.1 is a double and not an integer, the second statement, "sorry, variable $i is not an integer" will be displayed instead.
Two more functions, isset and unset are also useful for working with data types. isset checks to see whether or not a value has been assigned to a variable. unset will destroy the variable and remove it from memory.
<?
$i = 10;
if(isset($i)) // Checks if variable i has a value
{
echo("variable $i has a value"); // If defined, then display
} else {
echo("variable $i has no value"); // If not integer, then display
}
?>Since variable $i contains a value, the text "variable $i has a value" will be displayed. If we deleted the $i = 10; line, then the second echo statement displaying "variable $i has no value" will execute. Let's now take a look at the unset function, which allows us to remove a variable for memory:
<?
$i = 10;
unset($i); // Destroys variable $i
if(isset($i)) // Checks if variable $i has a value
{
echo("this should not display"); // If not destroyed, then display
}
?>In the first part of this sample code, we have defined a new integer variable, $i. Next, we used the unset function and pass in $i as its only parameter, which destroys the variable. Just to make sure it has been destroyed, we use the isset function to check it for a value. Since it shouldn't contain a value, the echo statement will never be executed and we will be left with a blank page.
We can also perform an action if, and only if, a particular variable is a specific data type, by using PHP’s "is_[variable type]" set of functions including is_double, is_string, is_array, or is_integer to check whether a specific variable matches the data type we're after. Let's look at an example.
<?
$i = 10;
if (is_integer($i))
echo("$i is an integer");
if (is_string($i))
echo("$i is a string");
if (is_double($i))
echo("$i is a double");
?>Since $i is an integer, the first if statement will evaluate to true, and "$i is an integer" will be displayed. Try adding quotes around the value of $i. The is_string function would evaluate to true, thus displaying "$I is a string".
Next: Conclusion >>
More PHP Articles
More By Steve Adcock