1.8. Understanding Data Types

Values stored in a variable or a constant are stored as a specific type of data. PHP provides eight data types:

  • Integer: A whole number

  • Floating-point number: A numeric value with decimal digits

  • String: A series of characters

  • Boolean: A value that can be either true or false

  • Array: A group of values in one variable

  • Object: A structure created with a class

  • Resource: A reference that identifies a connection

  • NULL: A value that represents no value

Integer, float, string, Boolean, and NULL data types are discussed in the following sections. Arrays are discussed in the section "Using Arrays," later in this chapter. Objects are discussed in Chapter 4 in this minibook.

When writing PHP scripts, you don't need to specify which data type you're storing. PHP determines the data type automatically. The following two statements store different data types:

$var1 = 123;
$var2 = "123";

The value for $var1 is stored as an integer. The value for $var2 is stored as a string because it's enclosed in quotes.

PHP converts data types automatically when it needs to. For instance, if you add two variables, one containing an integer and one containing a float, PHP converts the integer to a float so that it can add the two.

Occasionally, you might want to store a value as a data type different than the data type PHP automatically stores. You can set the data type for a variable with a cast, as follows:

$var3 = "222";
$var4 = (int) $var3;

This statement sets $var4 equal to the value ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.