Section 2.5. Basic Data Types

2.5. Basic Data Types

Eight different data types exist in PHP, five of which are scalar and each of the remaining three has its own uniqueness. The previously discussed variables can contain values of any of these data types without explicitly declaring their type. The variable "behaves" according to the data type it contains.

2.5.1. Integers

Integers are whole numbers and are equivalent in range as your C compiler's long value. On many common machines, such as Intel Pentiums, that means a 32-bit signed integer with a range between 2,147,483,648 to +2,147,483,647.

Integers can be written in decimal, hexadecimal (prefixed with 0x), and octal notation (prefixed with 0), and can include +/- signs.

Some examples of integers include

 240000 0xABCD 007 -100 


As integers are signed, the right shift operator in PHP always does a signed shift.

2.5.2. Floating-Point Numbers

Floating-point numbers (also known as real numbers) represent real numbers and are equivalent to your platform C compiler's double data type. On common platforms, the data type size is 8 bytes and it has a range of approximately 2.2E308 to 1.8E+308. Floating-point numbers include a decimal point and can include a +/- sign and an exponent value.

Examples of floating-point numbers include

 3.14 +0.9e-2 -170000.5 54.6E42 

2.5.3. Strings

Strings in PHP are a sequence of characters that are always internally null-terminated. However, unlike some other languages, such as C, PHP does not rely on the terminating null to calculate a string's length, but remembers its length internally. This allows for easy handling of binary data in PHPfor example, creating an image on-the-fly and outputting it to the browser. The maximum length of strings varies according to the platform and C compiler, but you can expect it to support at least 2GB. Don't write programs that test this limit because you're likely to first reach your memory limit.

When writing string values in your source code, you can use double quotes ("), single quotes (') or here-docs to delimit them. Each method is explained in this section. Double Quotes

Examples for double quotes:

 "PHP: Hypertext Pre-processor" "GET / HTTP/1.0\n" "1234567890" 

Strings can contain pretty much all characters. Some characters can't be written as is, however, and require special notation:






Double quote.




ASCII 0 (null).


Line feed.


Escape $ sign so that it is not treated as a variable but as the character $.

\{Octal #}

The character represented by the specified octal #for example, \70 represents the letter 8.

\x{Hexadecimal #}

The character represented by the specified hexadecimal #for example, \0x32 represents the letter 2.

An additional feature of double-quoted strings is that certain notations of variables and expressions can be embedded directly within them. Without going into specifics, here are some examples of legal strings that embed variables. The references to variables are automatically replaced with the variables' values, and if the values aren't strings, they are converted to their corresponding string representations (for example, the integer 123 would be first converted to the string "123").

 "The result is $result\n" "The array offset $i contains $arr[$i]" 

In cases, where you'd like to concatenate strings with values (such as variables and expressions) and this syntax isn't sufficient, you can use the . (dot) operator to concatenate two or more strings. This operator is covered in a later section. Single Quotes

In addition to double quotes, single quotes may also delimit strings. However, in contrast to double quotes, single quotes do not support all the double quotes' escaping and variable substitution.

The following table includes the only two escapings supported by single quotes:


Single quote.


Backslash, used when wanting to represent a backslash followed by a single quotefor example, \\'.


 'Hello, World' 'Today\'s the day' Here-Docs

Here-docs enable you to embed large pieces of text in your scripts, which may include lots of double quotes and single quotes, without having to constantly escape them.

The following is an example of a here-doc:

[View full width]

<<<THE_END PHP stands for "PHP: Hypertext Preprocessor". The acronym "PHP" is therefore, usually referred to as a recursive acronym because the long form contains the acronym itself. As this text is being written in a here-doc there is no need to escape the double quotes. THE_END

The strings starts with <<<, followed by a string that you know doesn't appear in your text. It is terminated by writing that string at the beginning of a line, followed by an optional semicolon (;), and then a required newline (\n). Escaping and variable substitution in here-docs is identical to double-quoted strings except that you are not required to escape double quotes. Accessing String Offsets

Individual characters in a string can be accessed using the $str{offset} notation. You can use it to both read and write string offsets. When reading characters, this notation should be used only to access valid indices. When modifying characters, you may access offsets that don't yet exist. PHP automatically sets that offset to the said character, and if this results in a gap between the ending of the original string and the offset of the new character, the gap filled with space characters (' ').

This example creates and prints the string "Andi" (in an awkward way):

 $str = "A"; $str{2} = "d"; $str{1} = "n"; $str = $str . "i"; print $str; 


For many cases, PHP has string manipulation functions which use efficient algorithms. You should first look at them before you access strings directly using string offsets. They are usually prefixed with str_. For more complex needs, the regular expressions functionsmost notably the pcre_ family of functionswill come in handy.


In PHP 4, you could use [] (square brackets) to access string offsets. This support still exists in PHP 5, and you are likely to bump into it often. However, you should really use the {} notation because it differentiates string offsets from array offsets and thus, makes your code more readable.

2.5.4. Booleans

Booleans were introduced for the first time in PHP 4 and didn't exist in prior versions. A Boolean value can be either true or false.

As previously mentioned, PHP automatically converts types when needed. Boolean is probably the type that other types are most often converted to behind the scenes. This is because, in any conditional code such as if statements, loops, and so on, types are converted to this scalar type to check if the condition is satisfied. Also, comparison operators result in a Boolean value.

Consider the following code fragment:

 $numerator = 1; $denominator = 5; if ($denominator == 0) {     print "The denominator needs to be a non-zero number\n"; } 

The result of the equal-than operator is a Boolean; in this case, it would be false and, therefore, the if() statement would not be entered.

Now, consider the next code fragment:

 $numerator = 1; $denominator = 5; if ($denominator) {     /* Perform calculation */ } else {     print "The denominator needs to be a non-zero number\n"; } 

You can see that no comparison operator was used in this example; however, PHP automatically internally converted $denominator or, to be more accurate, the value 5 to its Boolean equivalent, true, to perform the if() statement and, therefore, enter the calculation.

Although not all types have been covered yet, the following table shows truth values for their values. You can revisit this table to check for the types of Boolean value equivalents, as you learn about the remaining types.

Data Type

False Values

True Values



All non-zero values

Floating point


All non-zero values


Empty strings ()""

The zero string ()"0"

All other strings





If it does not contain any elements

If it contains at least one element







2.5.5. Null

Null is a data type with only one possible value: the NULL value. It marks variables as being empty, and it's especially useful to differentiate between the empty string and null values of databases.

The isset($variable) operator of PHP returns false for NULL, and true for any other data type, as long as the variable you're testing exists.

The following is an example of using NULL:

 $value = NULL; 

2.5.6. Resources

Resources, a special data type, represent a PHP extension resource such as a database query, an open file, a database connection, and lots of other external types.

You will never directly touch variables of this type, but will pass them around to the relevant functions that know how to interact with the specified resource.

2.5.7. Arrays

An array in PHP is a collection of key/value pairs. This means that it maps keys (or indexes) to values. Array indexes can be either integers or strings whereas values can be of any type (including other arrays).


Arrays in PHP are implemented using hash tables, which means that accessing a value has an average complexity of O(1). array() construct

Arrays can be declared using the array() language construct, which generally takes the following form (elements inside square brackets, [], are optional):

 array([key =>] value, [key =>] value, ...) 

The key is optional, and when it's not specified, the key is automatically assigned one more than the largest previous integer key (starting with 0). You can intermix the use with and without the key even within the same declaration.

The value itself can be of any PHP type, including an array. Arrays containing arrays give a similar result as multi-dimensional arrays in other languages.

Here are a few examples:

  • array(1, 2, 3) is the same as the more explicit array(0 => 1, 1 => 2, 2 => 3).

  • array("name" => "John", "age" => 28)

  • array(1 => "ONE", "TWO", "THREE") is equivalent to array(1 => "ONE", 2 => "TWO", 3 => "THREE").

  • array() an empty array.

Here's an example of a nested array() statement:

 array(array("name" => "John", "age" => 28), array("name" => "Barbara", "age" => 67)) 

The previous example demonstrates an array with two elements: Each one is a collection (array) of a person's information. Accessing Array Elements

Array elements can be accessed by using the $arr[key] notation, where key is either an integer or string expression. When using a constant string for key, make sure you don't forget the single or double quotes, such as $arr["key"]. This notation can be used for both reading array elements and modifying or creating new elements. Modifying/Creating Array Elements
 $arr1 = array(1, 2, 3); $arr2[0] = 1; $arr2[1] = 2; $arr2[2] = 3; print_r($arr1); print_r($arr2); 

The print_r() function has not been covered yet in this book, but when it is passed an array, it prints out the array's contents in a readable way. You can use this function when debugging your scripts.

The previous example prints

 Array (     [0] => 1     [1] => 2     [2] => 3 ) Array (     [0] => 1     [1] => 2     [2] => 3 ) 

So, you can see that you can use both the array() construct and the $arr[key] notation to create arrays. Usually, array() is used to declare arrays whose elements are known at compile-time, and the $arr[key] notation is used when the elements are only computed at runtime.

PHP also supports a special notation, $arr[], where the key is not specified. When creating new array offsets using this notation (fo example, using it as the l-value), the key is automatically assigned as one more than the largest previous integer key.

Therefore, the previous example can be rewritten as follows:

 $arr1 = array(1, 2, 3); $arr2[] = 1; $arr2[] = 2; $arr2[] = 3; 

The result is the same as in the previous example.

The same holds true for arrays with string keys:

 $arr1 = array("name" => "John", "age" => 28); $arr2["name"] = "John"; $arr2["age"] = 28; if ($arr1 == $arr2) {     print '$arr1 and $arr2 are the same' . "\n"; } 

The message confirming the equality of both arrays is printed. Reading array values

You can use the $arr[key] notation to read array values. The next few examples build on top of the previous example:

 print $arr2["name"]; if ($arr2["age"] < 35) {     print " is quite young\n"; } 

This example prints
 John is quite young 


As previously mentioned, using the $arr[] syntax is not supported when reading array indexes, but only when writing them. Accessing Nested Arrays (or Multi-Dimensional Arrays)

When accessing nested arrays, you can just add as many square brackets as required to reach the relevant value. The following is an example of how you can declare nested arrays:

[View full width]

$arr = array(1 => array("name" => "John", "age" => 28), array("name" => "Barbara", "age" => 67))

You could achieve the same result with the following statements:

 $arr[1]["name"] = "John"; $arr[1]["age"] = 28; $arr[2]["name"] = "Barbara"; $arr[2]["age"] = 67; 

Reading a nested array value is trivial using the same notation. For example, if you want to print John's age, the following statement does the trick:

 print $arr[1]["age"]; Traversing Arrays Using foreach

There are a few different ways of iterating over an array. The most elegant way is the foreach() loop construct.

The general syntax of this loop is

 foreach($array as [$key =>] [&] $value)         ... 

$key is optional, and when specified, it contains the currently iterated value's key, which can be either an integer or a string value, depending on the key's type.

Specifying & for the value is also optional, and it has to be done if you are planning to modify $value and want it to propagate to $array. In most cases, you won't want to modify the $value when iterating over an array and will, therefore, not need to specify it.

Here's a short example of the foreach() loop:

 $players = array("John", "Barbara", "Bill", "Nancy"); print  "The players are:\n"; foreach ($players as $key => $value) {        print "#$key = $value\n"; } 

The output of this example is
 The players are: #0 = John #1 = Barbara #2 = Bill #3 = Nancy 

Here's a more complicated example that iterates over an array of people and marks which person is considered old and which one is considered young:

[View full width]

$people = array(1 => array("name" => "John", "age" => 28), array("name" => "Barbara", "age" => 67)); foreach ($people as &$person) { if ($person["age"] >= 35) { $person["age group"] = "Old"; } else { $person["age group"] = "Young"; } } print_r($people);

Again, this code makes use of the print_r() function.

The output of the previous code is the following:

 Array (     [1] => Array         (             [name] => John             [age] => 28             [age group] => Young         )     [2] => Array         (             [name] => Barbara             [age] => 67             [age group] => Old         ) ) 

You can see that both the John and Barbara arrays inside the $people array were added an additional value with their respective age group. Traversing Arrays Using list() and each()

Although foreach() is the nicer way of iterating over an array, an additional way of traversing an array is by using a combination of the list() construct and the each() function:

 $players = array("John", "Barbara", "Bill", "Nancy"); reset($players); while (list($key, $val) = each($players)) {        print "#$key = $val\n"; } 

The output of this example is
 #0 = John #1 = Barbara #2 = Bill #3 = Nancy reset()

Iteration in PHP is done by using an internal array pointer that keeps record of the current position of the traversal. Unlike with foreach(), when you want to use each() to iterate over an array, you must reset() the array before you start to iterate over it. In general, it is best for you to always use foreach() and not deal with this subtle nuisance of each() traversal. each()

The each() function returns the current key/value pair and advances the internal pointer to the next element. When it reaches the end of of the array, it returns a booloean value of false. The key/value pair is returned as an array with four elements: the elements 0 and "key", which have the value of the key, and elements 1 and "value", which have the value of the value. The reason for duplication is that, if you're accessing these elements individually, you'll probably want to use the names such as $elem["key"] and $elem["value"]:

 $ages = array("John" => 28, "Barbara" => 67); reset($ages); $person = each($ages); print $person["key"]; print " is of age "; print $person["value"]; 

This prints
 John is of age 28 

When we explain how the list() construct works, you will understand why offsets 0 and 1 also exist. list()

The list() construct is a way of assigning multiple array offsets to multiple variables in one statement:

 list($var1, $var2, ...) = $array; 

The first variable in the list is assigned the array value at offset 0, the second is assigned offset 1, and so on. Therefore, the list() construct translates into the following series of PHP statements:

 $var1 = $array[0]; $var2 = $array[1]; ... 

As previously mentioned, the indexes 0 and 1 returned by each() are used by the list() construct. You can probably already guess how the combination of list() and each() work.

Consider the highlighted line from the previous $players traversal example:

 $players = array("John", "Barbara", "Bill", "Nancy"); reset($players); while (list($key, $val) = each($players)) {        print "#$key = $val\n"; } 

What happens in the boldfaced line is that during every loop iteration, each() returns the current position's key/value pair array, which, when examined with print_r(), is the following array:

 Array (     [1] => John     [value] => John     [0] => 0     [key] => 0 ) 

Then, the list() construct assigns the array's offset 0 to $key and offset 1 to $val. Additional Methods for Traversing Arrays

You can use other functions to iterate over arrays including current() and next(). You shouldn't use them because they are confusing and are legacy functions. In addition, some standard functions allow all sorts of elegant ways of dealing with arrays such as array_walk(), which is covered in a later chapter.

2.5.8. Constants

In PHP, you can define names, called constants, for simple values. As the name implies, you cannot change these constants once they represent a certain value. The names for constants have the same rules as PHP variables except that they don't have the leading dollar sign. It is common practice in many programming languagesincluding PHPto use uppercase letters for constant names, although you don't have to. If you wish, which we do not recommend, you may define your constants as case-insensitive, thus not requiring code to use the correct casing when referring to your constants.


Only use case-sensitive constants both to be consistent with accepted coding standards and because it is unclear if case-insensitive constants will continued to be supported in future versions of PHP.

Unlike variables, constants, once defined, are globally accessible. You don't have to (and can't) redeclare them in each new function and PHP file.

To define a constant, use the following function:

 define("CONSTANT_NAME", value [, case_sensitivity]) 


  • "CONSTANT_NAME" is a string.

  • value is any valid PHP expression excluding arrays and objects.

  • case_sensitivity is a Boolean (true/false) and is optional. The default is true.

An example for a built-in constant is the Boolean value TRue, which is registered as case-insensitive.

Here's a simple example for defining and using a constant:

 define("MY_OK", 0); define("MY_ERROR", 1); ... if ($error_code == MY_ERROR) {     print("There was an error\n"); } 

    PHP 5 Power Programming
    PHP 5 Power Programming
    ISBN: 013147149X
    EAN: 2147483647
    Year: 2003
    Pages: 240

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: