start page | rating of books | rating of authors | reviews | copyrights

Programming PHPProgramming PHPSearch this book

2.2. Data Types

PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point numbers, strings, and booleans. Two are compound (collection) types: arrays and objects. The remaining two are special types: resource and NULL. Numbers, booleans, resources, and NULL are discussed in full here, while strings, arrays, and objects are big enough topics that they get their own chapters (Chapter 4, Chapter 5, and Chapter 6).

2.2.1. Integers

Integers are whole numbers, like 1, 12, and 256. The range of acceptable values varies according to the details of your platform but typically extends from -2,147,483,648 to +2,147,483,647. Specifically, the range is equivalent to the range of the long data type of your C compiler. Unfortunately, the C standard doesn't specify what range that long type should have, so on some systems you might see a different integer range.

Integer literals can be written in decimal, octal, or hexadecimal. Decimal values are represented by a sequence of digits, without leading zeros. The sequence may begin with a plus (+) or minus (-) sign. If there is no sign, positive is assumed. Examples of decimal integers include the following:

1998
-641
+33

Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers, octal numbers can be prefixed with a plus or minus. Here are some example octal values and their equivalent decimal values:

0755      // decimal 493
+010      // decimal 8

Hexadecimal values begin with 0x, followed by a sequence of digits (0-9) or letters (A-F). The letters can be upper- or lowercase but are usually written in capitals. Like decimal and octal values, you can include a sign in hexadecimal numbers:

0xFF        // decimal 255
0x10        // decimal 16
-0xDAD1     // decimal -56017

If you try to store a too-large integer in a variable, it will automatically be turned into a floating-point number.

Use the is_int( ) function (or its is_integer( ) alias) to test whether a value is an integer:

if (is_int($x)) {
    // $x is an integer
}

2.2.2. Floating-Point Numbers

Floating-point numbers (often referred to as real numbers) represent numeric values with decimal digits. Like integers, their limits depend on your machine's details. PHP floating-point numbers are equivalent to the range of the double data type of your C compiler. Usually, this allows numbers between 1.7E-308 and 1.7E+308 with 15 digits of accuracy. If you need more accuracy or a wider range of integer values, you can use the BC or GMP extensions. See Appendix B for an overview of the BC and GMP extensions.

PHP recognizes floating-point numbers written in two different formats. There's the one we all use every day:

3.14
0.017
-7.1

but PHP also recognizes numbers in scientific notation:

0.314E1      // 0.314*101, or 3.14
17.0E-3      // 17.0*10-3, or 0.017

Floating-point values are only approximate representations of numbers. For example, on many systems 3.5 is actually represented as 3.4999999999. This means you must take care to avoid writing code that assumes floating-point numbers are represented completely accurately, such as directly comparing two floating-point values using ==. The normal approach is to compare to several decimal places:

if (int($a * 1000) == int($b * 1000)) { 
  // numbers equal to three decimal places

Use the is_float( ) function (or its is_real( ) alias) to test whether a value is a floating point number:

if (is_float($x)) {
    // $x is a floating-point number
}

2.2.3. Strings

Because strings are so common in web applications, PHP includes core-level support for creating and manipulating strings. A string is a sequence of characters of arbitrary length. String literals are delimited by either single or double quotes:

'big dog'
"fat hog"

Variables are expanded within double quotes, while within single quotes they are not:

$name = "Guido";
echo "Hi, $name\n";       
echo 'Hi, $name';       
Hi, Guido
Hi, $name

Double quotes also support a variety of string escapes, as listed in Table 2-2.

Table 2-2. Escape sequences in double-quoted strings

Escape sequence

Character represented

\"

Double quotes

\n

Newline

\r

Carriage return

\t

Tab

\\

Backslash

\$

Dollar sign

\{

Left brace

\}

Right brace

\[

Left bracket

\]

Right bracket

\0 through \777

ASCII character represented by octal value

\x0 through \xFF

ASCII character represented by hex value

A single-quoted string only recognizes \\ to get a literal backslash and \' to get a literal single quote:

$dos_path = 'C:\\WINDOWS\\SYSTEM';
$publisher = 'Tim O\'Reilly';
echo "$dos_path $publisher\n";
C:\WINDOWS\SYSTEM Tim O'Reilly

To test whether two strings are equal, use the == comparison operator:

if ($a == $b) { echo "a and b are equal" }

Use the is_string( ) function to test whether a value is a string:

if (is_string($x)) {
    // $x is a string
}

PHP provides operators and functions to compare, disassemble, assemble, search, replace, and trim strings, as well as a host of specialized string functions for working with HTTP, HTML, and SQL encodings. Because there are so many string-manipulation functions, we've devoted a whole chapter (Chapter 4) to covering all the details.

2.2.4. Booleans

A boolean value represents a "truth value"—it says whether something is true or not. Like most programming languages, PHP defines some values as true and others as false. Truth and falseness determine the outcome of conditional code such as:

if ($alive) { ... }

In PHP, the following values are false:

Any value that is not false is true, including all resource values (which are described later, in Section 2.2.7).

PHP provides true and false keywords for clarity:

$x = 5;         // $x has a true value
$x = true;      // clearer way to write it
$y = "";        // $y has a false value
$y = false;     // clearer way to write it

Use the is_bool( ) function to test whether a value is a boolean:

if (is_bool($x)) {
    // $x is a boolean
}

2.2.5. Arrays

An array holds a group of values, which you can identify by position (a number, with zero being the first position) or some identifying name (a string):

$person[0] = "Edison";
$person[1] = "Wankel";
$person[2] = "Crapper";
$creator['Light bulb'] = "Edison";
$creator['Rotary Engine'] = "Wankel";
$creator['Toilet'] = "Crapper";

The array( ) construct creates an array:

$person = array('Edison', 'Wankel', 'Crapper');
$creator = array('Light bulb'    => 'Edison',
                 'Rotary Engine' => 'Wankel',
                 'Toilet'        => 'Crapper');

There are several ways to loop across arrays, but the most common is a foreach loop:

foreach ($person as $name) {
  echo "Hello, $name\n";
}
foreach ($creator as $invention => $inventor) {
  echo "$inventor created the $invention\n";
}
Hello, Edison
Hello, Wankel
Hello, Crapper
Edison created the Light bulb
Wankel created the Rotary Engine
Crapper created the Toilet

You can sort the elements of an array with the various sort functions:

sort($person);
// $person is now array('Crapper', 'Edison', 'Wankel')
asort($creator);
// $creator is now array('Toilet'        => 'Crapper',
//                       'Light bulb'    => 'Edison',
//                       'Rotary Engine' => 'Wankel');

Use the is_array( ) function to test whether a value is an array:

if (is_array($x)) {
    // $x is an array
}

There are functions for returning the number of items in the array, fetching every value in the array, and much more. Arrays are described in Chapter 5.

2.2.6. Objects

PHP supports object-oriented programming (OOP). OOP promotes clean modular design, simplifies debugging and maintenance, and assists with code reuse.

Classes are the unit of object-oriented design. A class is a definition of a structure that contains properties (variables) and methods (functions). Classes are defined with the class keyword:

class Person {
  var $name = '';
  function name ($newname = NULL) {
    if (! is_null($newname)) {
      $this->name = $newname;
    }
    return $this->name;
  }
}

Once a class is defined, any number of objects can be made from it with the new keyword, and the properties and methods can be accessed with the -> construct:

$ed = new Person;
$ed->name('Edison');
printf("Hello, %s\n", $ed->name);
$tc = new Person;
$tc->name('Crapper');
printf("Look out below %s\n", $tc->name);
Hello, Edison
Look out below Crapper

Use the is_object( ) function to test whether a value is an object:

if (is_object($x)) {
    // $x is an object
}

Chapter 6 describes classes and objects in much more detail, including inheritance, encapsulation (or the lack thereof ), and introspection.

2.2.7. Resources

Many modules provide several functions for dealing with the outside world. For example, every database extension has at least a function to connect to the database, a function to send a query to the database, and a function to close the connection to the database. Because you can have multiple database connections open at once, the connect function gives you something by which to identify that connection when you call the query and close functions: a resource.

Resources are really integers under the surface. Their main benefit is that they're garbage collected when no longer in use. When the last reference to a resource value goes away, the extension that created the resource is called to free any memory, close any connection, etc. for that resource:

$res = database_connect( );   // fictitious function
database_query($res);
$res = "boo";                // database connection automatically closed

The benefit of this automatic cleanup is best seen within functions, when the resource is assigned to a local variable. When the function ends, the variable's value is reclaimed by PHP:

function search ( ) {
  $res = database_connect( );
  $database_query($res);
}

When there are no more references to the resource, it's automatically shut down.

That said, most extensions provide a specific shutdown or close function, and it's considered good style to call that function explicitly when needed rather than to rely on variable scoping to trigger resource cleanup.

Use the is_resource( ) function to test whether a value is a resource:

if (is_resource($x)) {
    // $x is a resource
}

2.2.8. NULL

There's only one value of the NULL data type. That value is available through the case-insensitive keyword NULL. The NULL value represents a variable that has no value (similar to Perl's undef or Python's None):

$aleph = "beta";
$aleph = null;      // variable's value is gone
$aleph = Null;      // same
$aleph = NULL;      // same

Use the is_null( ) function to test whether a value is NULL—for instance, to see whether a variable has a value:

if (is_null($x)) {
    // $x is NULL
}


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.