[ Team LiB ] Previous Section Next Section

Data Types

Different types of data take up different amounts of memory and can 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, which means it calculates data types as data is assigned to each variable. This is a mixed blessing. On the one hand, it means that variables can be used flexibly, holding a string at one point and an integer at another. On the other hand, this can lead to problems in larger scripts if you expect a variable to hold one data type when, in fact, it holds something completely different. You might have created code designed to work with an array variable, for example. If the variable in question contains a number value instead, errors might occur when the code attempts to perform array-specific operations on the variable.

Table 4.1 shows the six standard data types available in PHP.

Table 4.1. Standard Data Types

Type

Example

Description

Integer

5

A whole number

Double

3.234

A floating-point number

String

"hello"

A collection of characters

Boolean

true

One of the special values true or false

Object

 

See Hour 9, "Objects"

Array

 

See Hour 7, "Arrays"

Of PHP's six standard data types, we will leave arrays and objects for Hours 7 and 9.

PHP also provides two special data types, which are listed in Table 4.2.

Table 4.2. Special Data Types

Type

Description

Resource

Reference to a third-party resource (a database, for example)

NULL

An uninitialized variable

Resource types are often returned by functions that deal with external applications or files. You will see examples of resource types throughout the book. The type NULL is reserved for variables that have not been initialized (that is, they have not yet had a value assigned to them).

You can use PHP's built-in function gettype () to acquire 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 4.1 assigns five different data types to a single variable, testing it with gettype() each time.

graphics/bytheway_icon.gif

You can read more about calling functions in Hour 6, "Functions."


Listing 4.1 Displaying the Type of a Variable
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 4.1 Testing the type of a variable</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $testing; // declare without assigning
12: print gettype( $testing ); // NULL
13: print "<br />";
14: $testing = 5;
15: print gettype( $testing ); // integer
16: print "<br />";
17: $testing = "five";
18: print gettype( $testing ); // string
19: print "<br />";
20: $testing = 5.0;
21: print gettype( $testing ); // double
22: print "<br />";
23: $testing = true;
24: print gettype( $testing ); // boolean
25: print "<br />";
26: ?>
27: </div>
28: </body>

This script produces the following:


NULL
integer
string
double
boolean

When we declare our $testing variable in line 11, we do not assign a value to it. So, when we first use the gettype() function to test the variable in line 12, we get the string NULL. After this, we assign values to $testing by using = before passing it to gettype(). An integer (5), assigned to the $testing variable in line 14, is a whole or real number. In simple terms, it can be said to be a number without a decimal point. A string ("five"), assigned to the $testing variable in line 17, is a collection of characters. When you work with strings in your scripts, they should always be surrounded by double quotation marks (") or single quotation marks ('). A double (5.0), assigned to the $testing variable in line 20, is a floating-point number. That is, it's a number that includes a decimal point. A boolean (true), assigned to the $testing variable in line 23, can be one of two special values: true or false.

graphics/bytheway_icon.gif

There is a difference between double quotation marks and single quotation marks when used with strings. Double quotation marks allow the parsing of variables. If you include a variable within double quotation marks the PHP engine substitutes the variable's value, like so:


$name = "john";
print "hello, $name"; // hello, john

If you use single quotation marks to enclose the same string, the variable is not substituted:


print 'hello, $name'; // hello, $name

Double-quoted strings are also parsed for escape characters. Escape characters take on or lose special meaning when preceded by a backslash (\) character. Notable among these are \n for a newline character, \t for a tab, \" to print a double-quoted character within a double-quoted string, \\ to print a backslash, and \$ to print a dollar sign (so that it is not mistaken for the start of a variable).

As a rule of thumb, if you want a string to be output exactly as you typed it, you can use single quotation marks. This can help your code to run more quickly because the interpreter does not have to parse the string. If you want to take advantage of escape characters such as \n and use variable substitution, you should use double quotation marks.


graphics/bytheway_icon.gif

Prior to PHP 4, there was no boolean type. Although true was used, it was actually a constant (a special kind of variable that we will cover later in this chapter) with the integer value of 1.

Both NULL and Resource types were added with PHP 4.


Displaying Type Information with var_dump()

gettype() is a specialized tool. It does what it promises and returns a variable's type. var_dump() tells you a variable's type and its contents. More than that, for complex types such as arrays and objects, var_dump() provides information about all the types contained within the variable, as well as about the variable itself.

So, by altering line 11 of Listing 4.1, we can put var_dump() to the test:


$testing = 5;
var_dump( $testing );

This fragment gives us the following result:


int(5)

This tells us that the variable $testing contains an integer and that the value of that integer is 5. Notice that we did not need to print the result of var_dump(); this is because the function prints its findings directly to the browser or command line.

Testing for a Specific Data Type

gettype() is useful for debugging because it tells you exactly what type any variable is. Often, though, you will want to check only whether a variable contains a specific type. PHP provides a special function corresponding to each data type. These functions accept a variable or value and return a boolean. Table 4.3 lists these functions.

Table 4.3. Functions to Test Data Types

Function

Description

is_array()

Returns true if the argument is an array

is_bool()

Returns true if the argument is boolean

is_double()

Returns true if the argument is a double

is_int()

Returns true if the argument is an integer

is_object()

Returns true if the argument is an object

is_string()

Returns true if the argument is a string

is_null()

Returns true if the argument is null

is_resource()

Returns true if the argument is a resource

In Hour 5, "Going with the Flow," we examine the if statement, which enables you to alter the behavior of a script according to the results of a test. These type testing functions are frequently used in conjunction with if statements to enforce the type of a variable passed to a function or object method.

Changing Type with settype()

PHP provides the function settype() to change the type of a variable. To use settype(), you must place the variable to change (and the type to change it to) between the parentheses and separate them by commas. Listing 4.2 converts the value 3.14 (a double) to the four types we are covering in this hour.

Listing 4.2 Changing the Type of a Variable with settype()
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title> Listing 4.2 Changing the Type of a Variable with settype()</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $undecided = 3.14;
12: print gettype( $undecided ); // double
13: print " -- $undecided<br />"; // 3.14
14: settype( $undecided, string );
15: print gettype( $undecided ); // string
16: print " -- $undecided<br />"; // 3.14
17: settype( $undecided, int );
18: print gettype( $undecided ); // integer
19: print " -- $undecided<br />"; // 3
20: settype( $undecided, double );
21: print gettype( $undecided ); // double
22: print " -- $undecided<br />"; // 3.0
23: settype( $undecided, bool );
24: print gettype( $undecided ); // boolean
25: print " -- $undecided<br />"; // 1
26: ?>
27: </div>
28: </body>
29: </html>

In each case, we use gettype() to confirm that the type change worked and then print the value of the variable $undecided to the browser. When we convert the string 3.14 to an integer in line 17, any information beyond the decimal point is lost forever. That's why $undecided still contains 3 after we have changed it back to a double in line 20. Finally, in line 23, 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 as an empty string, so in line 21, $undecided is printed as 1.

Changing Type by Casting

By placing the name of a data type in parentheses in front of a variable, you create a copy of that variable's value converted to the data type specified.

The principle difference between settype() and a cast is the fact that casting produces a copy, leaving the original variable untouched. Listing 4.3 illustrates this.

Listing 4.3 Casting a Variable
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title> Listing 4.3 Casting a Variable</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $undecided = 3.14;
12: $holder = ( double ) $undecided;
13: print gettype( $holder ) ; // double
14: print " -- $holder<br />"; // 3.14
15: $holder = ( string ) $undecided;
16: print gettype( $holder ); // string
17: print " -- $holder<br />"; // 3.14
18: $holder = ( integer ) $undecided;
19: print gettype( $holder ); // integer
20: print " -- $holder<br />"; // 3
21: $holder = ( double ) $undecided;
22: print gettype( $holder ); // double
23: print " -- $holder<br />"; // 3.14
24: $holder = ( boolean ) $undecided;
25: print gettype( $holder ); // boolean
26: print " -- $holder<br />"; // 1
27: ?>
28: </div>
29: </body>
30: </html>

We never actually change the type of $undecided, which remains a double throughout. We illustrate this on line 25 by using the gettype() function to output the type of $undecided.

In fact, by casting $undecided, we create a copy that is then converted to the type we specify. This new value is then stored in the variable $holder, first in line 12 and then also in lines 15, 18, 21, and 24. Because we are working with a copy of $undecided, we never discard any information from it as we did in lines 17 and 23 of Listing 4.2.

Now that we can change the contents of a variable from one type to another, either using settype() or a cast, we should consider why this might be useful. It is certainly not a procedure you will use often because PHP automatically casts for you when the context requires. However, an automatic cast is temporary, and you might want to make a variable persistently hold a particular data type.

Numbers typed in to an HTML form by a user are made available to your script as a string. If you try to add two strings containing numbers, PHP helpfully converts the strings into numbers while the addition is taking place. So


"30cm" + "40cm"

produces the integer 70. In casting the strings, PHP ignores the non-numeric characters. However, you might want to clean up your user input yourself. Imagine that a user has been asked to submit a number. We can simulate this by declaring a variable and assigning to it, like so:


$test = "30cm";

As you can see, the user has mistakenly added units to the number. We can ensure that the user input is clean by casting it to an integer, as shown here:


$test = (integer)$test;
print "Your imaginary box has a width of $test centimeters";



More Ways of Changing Type

You have already seen two ways of converting data types: You can cast a value or use the settype() function. In addition to these techniques, PHP provides functions to convert values into integers, doubles, and strings. These functions accept values of any type apart from array or object and return a converted value. Table 4.4 lists these functions.

Table 4.4. Functions to Convert Data Types

Function

Description

doubleval()

Accepts a value and returns double equivalent

intval()

Accepts a value and returns integer equivalent

strval()

Accepts a value and returns string equivalent

Why Test Type?

Why might it be useful to know the type of a variable? Many circumstances occur in programming in which data is passed to you from another source. In Hour 6, for example, you learn how to create functions in your scripts. Functions can accept information from calling code in the form of arguments. For the function to work with the data it is given, you often need to first check that it has been given values of the correct data type. A function that is expecting a resource, for example, will not work well when passed a string.

    [ Team LiB ] Previous Section Next Section