Different types of data take up different amounts of memory and may be treated differently when they are manipulated in a script. Some programming languages therefore demand that the programmer declare in advance which type of data a variable will contain. By contrast, PHP is loosely typed, meaning that it will determine the data type at the time data is assigned to each variable.
This automatic typing is a mixed blessing. On the one hand, it means that variables can be used flexiblyin once instance a variable can hold a string and then later in the script it could hold an integer or some other type. On the other hand, this can lead to problems in larger scripts if you are specifically expecting a variable to hold one data type when in fact it holds something completely different. For example, suppose you have created code that is designed to manipulate an array variable. If the variable in question instead contains a number value, and no array structure is in place, errors will occur when the code attempts to perform array-specific operations on the variable.
Table 5.1 shows the eight standard data types available in PHP.
Resource types are often returned by functions that deal with external applications or files. For example, you will see references to "the MySQL resource ID" in Chapter 17, "Interacting with MySQL Using PHP." The NULL type is reserved for variables that have been declared, but no value has been assigned to them.
You can use the built-in PHP function called gettype() to test the type of any variable. If you place a variable between the parentheses of the function call, gettype() returns a string representing the relevant type. Listing 5.1 assigns different data types to a single variable, testing it with gettype() each time. The comments in the code show you where the script is in the process.
By the Way
You can read more about calling functions in Chapter 7, "Working with Functions."
Listing 5.1. Testing the Type of a Variable
1: <?php 2: $testing; // declare without assigning 3: echo gettype($testing); // null 4: echo "<br>"; 5: $testing = 5; 6: echo gettype($testing); // integer 7: echo "<br>"; 8: $testing = "five"; 9: echo gettype($testing); // string 10: echo "<br>"; 11: $testing = 5.024; 12: echo gettype($testing); // double 13: echo "<br>"; 14: $testing = true; 15: echo gettype($testing); // boolean 16: echo "<br>"; 17: $testing = array('apple', 'orange', 'pear'); 18: echo gettype($testing); // array 29: echo "<br>"; 20: ?>
Put these lines into a text file called gettype.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:
NULL integer string double boolean array
When we declare the $testing variable in line 2, we do not assign a value to it, so when we first use the gettype() function to test the variable in line 3, we get the string NULL. After this, we assign values to $testing by using the = sign before passing it to gettype(). An integer, assigned to the $testing variable in line 5, is a whole or real number. In simple terms, you can think of it as a number without a decimal point. A string, assigned to the $testing variable in line 8, is a collection of characters. When you work with strings in your scripts, they should always be surrounded by double or single quotation marks (" or '). A double, assigned to the $testing variable in line 11, is a floating-point number (that is, a number that includes a decimal point). A Boolean, assigned to the $testing variable in line 14, can have one of two special values: TRue or false. In line 17, an array is created using the array() function, which you'll learn more about in Chapter 8, "Working with Arrays and Objects." This particular array contains three items, and the script dutifully reports $testing to have a type of "array."
Changing Type with settype()
PHP also provides the function settype(), which is used to change the type of a variable. To use settype(), you place the variable to change and the type to change it to between the parentheses and separate them with a comma, such as
settype($variabletochange, 'new type');
Listing 5.2 converts the value 3.14 (a float) to each of the four standard types that we focus on in this chapter.
Listing 5.2. Changing the Type of a Variable with settype()
1: <?php 2: $undecided = 3.14; 3: echo gettype($undecided); // double 4: echo " is $undecided<br>"; // 3.14 5: settype($undecided, 'string'); 6: echo gettype($undecided); // string 7: echo " is $undecided<br>"; // 3.14 8: settype($undecided, 'integer'); 9: echo gettype($undecided); // integer 10: echo " is $undecided<br>"; // 3 11: settype($undecided, 'double'); 12: echo gettype($undecided); // double 13: echo " is $undecided<br>"; // 3 14: settype($undecided, 'bool'); 15: echo gettype($undecided); // boolean 16: echo " is $undecided<br>"; // 1 17: ?>
By the Way
Per the PHP manual, "double" is returned in case of a float, and not simply "float". Your eyes are not deceiving you.
In each case, we use gettype() to confirm the new type, and then print the value of the variable $undecided to the browser using echo. When we convert the string "3.14" to an integer in line 5, any information beyond the decimal point is lost forever. That's why $undecided contains 3 after we change it back to a double in line 11. Finally, in line 14, we convert $undecided to a Boolean. Any number other than 0 becomes true when converted to a Boolean. When printing a Boolean in PHP, true is represented as 1 and false is represented as an empty string, so in line 16, $undecided is printed as 1.
Put these lines into a text file called settype.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:
double is 3.14 string is 3.14 integer is 3 double is 3 boolean is 1
Changing Type by Casting
The principal difference between using settype() to change the type of an existing variable, and changing type by casting is the fact that casting produces a copy, leaving the original variable untouched. To change type through casting, you indicate the name of a data type, in parentheses, in front of the variable you are copying. For example, the line below creates a copy of the $originalvar variable, with a specific type (integer) and a new name $newvar. The $originalvar variable will still be available, and will be its original type; $newvar is a completely new variable.
$newvar = (integer) $originalvar
Listing 5.3 illustrates changing type through casting.
Listing 5.3. Casting a Variable
1: <?php 2: $undecided = 3.14; 3: $holder = (double) $undecided; 4: echo gettype($holder) ; // double 5: echo " is $holder<br>"; // 3.14 6: $holder = (string) $undecided; 7: echo gettype($holder); // string 8: echo " is $holder<br>"; // 3.14 9: $holder = (integer) $undecided; 10: echo gettype($holder); // integer 11: echo " is $holder<br>"; // 3 12: $holder = (double) $undecided; 13: echo gettype($holder); // double 14: echo " is $holder<br>"; // 3.14 15: $holder = (boolean) $undecided; 16: echo gettype($holder); // boolean 17: echo " is $holder<br>"; // 1 18: echo "<hr>"; 19: echo "original variable type: "; 20: echo gettype($undecided); // double 21: ?>
We never actually change the type of the $undecided variable, which remains a double throughout this script, as illustrated on line 20, where we use the gettype() function to determine the type of $undecided.
In fact, by casting $undecided, we create a copy that is then converted to the type specified at the time of the cast, and stored in the variable $holder. This casting occurs first in line 3, and also in lines 6, 9, 12, and 15. Because we are only working with a copy of $undecided, and not the original variable, it never lost its original value, as the $undecided variable did in line 8 of Listing 5.2, when its type changed from a string to an integer.
Put the contents of Listing 5.3 into a text file called testtype.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:
double is 3.14 string is 3.14 integer is 3 double is 3.14 boolean is 1 original variable type: double
Now that you've seen how to change the contents of a variable from one type to another, using either settype() or by casting, consider why this might be useful. It is not a procedure that you will have to use often, because PHP will automatically cast your variables for you when the context of the script requires a change. However, such an automatic cast is temporary, and you might wish to make a variable persistently hold a particular data typethus, the ability to specifically change types.
For example, the numbers that a user types into an HTML form will be made available to your script as the "string" type. If you try to add two strings together, because they contain numbers, PHP will helpfully convert these strings into numbers while the addition is taking place. So
"30cm" + "40cm"
will provide an answer of 70.
By the Way
The generic term "number" is used here to mean integers and floats. If the user input is in float form, and the strings added together were "3.14cm" and "4.12cm", the answer provided would be 7.26.
During the casting of a string into an integer or float, PHP will ignore any nonnumeric characters. The string will be truncated with any characters from the location of the first non-numeric character onward ignored. So, while "30cm" is transformed into "30", the string "6ft2in" becomes just 6, as the rest of it evaluates to zero.
You might want to clean up the user input yourself, and use it in a particular way in your script. Imagine that the user has been asked to submit a number. We can simulate this by declaring a variable and assigning to it:
$test = "30cm";
As you can see, the user has added units to their numberinstead of entering "30", the user has enter "30cm. "You can make sure that the user input is clean by casting it as an integer:
$newtest = (integer) $test; echo "Your imaginary box has a width of $newtest centimeters.";
The resulting output would be
Your imaginary box has a width of 30 centimeters.
Had the the user input not been cast, and the value of the original variable, $test, been used in place of $newtest when priting the statement regarding the width of a box, the result would have been:
Your imaginary box has a width of 30cm centimeters.
This output looks strange; in fact, it looks like parroted user input that hadn't been cleaned up (which is is).
Why Test Type?
Why might it be useful to know the type of a variable? There are often circumstances in programming in which data is passed to you from another source. In Chapter 7, you will learn how to create functions in your scripts, and data is often passed between one or more functions, as they can accept information from calling code in the form of arguments. For the function to work with the data it is given, it is a good idea to first verify that it has been given values of the correct data type. For example, a function that is expecting data that has a type of "resource" will not work well when passed a string.