The Building Blocks: Data Types, Literals, Variables, and Constants | WebReference

The Building Blocks: Data Types, Literals, Variables, and Constants


[next]

The Building Blocks:
Data Types, Literals, Variables, and Constants

By Ellie Quigley

"One man's constant is another man's variable." —Alan Perlis

Data Types

A program can do many things, including perform calculations, sort names, prepare phone lists, display images, play chess, ad infinitum. To do anything, however, the program works with the data that is given to it. Data types specify what kind of data, such as numbers and characters, can be stored and manipulated within a program. PHP supports a number of fundamental basic data types, such as integers, floats, and strings. Basic data types are the simplest building blocks of a program. They are called scalars and can be assigned a single literal value such as a number, 5.7, or a string of characters, such as "hello", a date and time, or a boolean (true/false). See Figure 4.1.

PHP also supports composite data types, such as arrays and objects. Composite data types represent a collection of data, rather than a single value (see Figure 4.2). The composite data types are discussed in Chapter 8, "Arrays," and Chapter 17, "Objects."

Figure 4.1 - Scalars hold one value

Figure 4.2 - Arrays and objects hold multiple values

The different types of data are commonly stored in variables. Examples of PHP variables are $num = 5 or $name = "John" where variables $num and $name are assigned an integer and a string, respectively. Variables hold values that can change throughout the program, whereas once a constant is defined, its value does not change. PHP_VERSION and PHP_OS are examples of predefined PHP constants. The use of PHP variables and constants is addressed in "Variables" on page 70 and "Constants" on page 99 of this chapter.

PHP supports four core data types:

  • Integer
  • Float (also called double)
  • String
  • Boolean

In addition to the four core data types, there are four other special types:

  • Null
  • Array
  • Object
  • Resources

Numeric Literals

PHP supports both integers and floating-point numbers. See Example 4.1.

  • Integers—Integers are whole numbers and do not contain a decimal point; for example, 123 and –6. Integers can be expressed in decimal (base 10), octal (base 8), and hexadecimal (base 16), and are either positive or negative values.
  • Floating-point numbers—Floating-point numbers, also called doubles or reals, are fractional numbers such as 123.56 or –2.5. They must contain a decimal point or an exponent specifier, such as 1.3e–2. The letter "e" can be either upper or lowercase.

PHP numbers can be very large (the size depends on your platform), but a precision of 14 decimal digits is a common value or (~1.8e308).

Example 4.1

Example 4.2

Figure 4.3 Output from Example 4.2.


[next]

URL: