Many programmers with experience in other languages find working with types in PHP a slightly different and occasionally quirky experience. PHP is a richly typed language, where each piece of data has a type associated with it, but variables are not declared as having a particular typethe language engine determines the type to use based on a set of rules ( leading some people to call it dynamically typed instead). We will now introduce the most basic types and discuss how they are used.
There are two basic types of numbers in the language: integer (int ) and float (float). While many languages distinguish between single and double-precision floating-point numbers, PHP does notthey are all 64-bit floating-point numbers with approximately 14 digits of precision. PHP does, however, support the keyword double in addition to float for compatibility.
Integers are specified in code in octal (base-8), decimal (base-10), or hexadecimal (base-16) notations.
<?php $abc = 123; // decimal $def = -123; $ghi = 0173; // octal, value is 123 in decimal $jkl = -0173; // octal, value is -123 in decimal $mno = 0x7b; // hexadecimal, 123 $pqr = -0x7B; // hexadecimal, -123 ?>
Integer precision varies largely by the underlying operating system, but 32 bits is common. There are no unsigned integers in PHP, so the maximum value for an integer is typically larger than 2 billion. However, unlike other languages that overflow large positive integers into large negative integers, PHP actually overflows integers to floating-point numbers.
<?php $large = 2147483647; var_dump($large); $large = $large + 1; var_dump($large) ?>
The output of this script is
In the previous snippet of code, we introduce the var_dump function, a powerful debugging tool used to see both the type and value of a variable in PHP. We will return to this later in the chapter in the section titled "Some Very Useful Functions."
Even though we will discuss arithmetic operators such as addition, multiplication, and subtraction in Chapter 2, in the section titled "Expressions and Operators," we will take time now to note that there is no integer division in PHP. Unlike some other languages, for which the expression
5 / 2
would yield an integer result with the value 2, PHP would return the value 2.5, typed as float. If you want the integer value result of a division operation, you need to cast the value to an integer (see the section "Type Conversions" in Chapter 2) or use the round function, which you can learn about via the PHP Online Manual.
Floating-point variables can be input in a few different ways:
<?php $floatvar1 = 7.555; $floatvar2 = 6.43e2; // same as 643.0 $floatvar3 = 1.3e+4; // same as 13000.0; $floatvar4 = 5.555e-4; // same as 0.0005555; $floatvar5 = 1000000000000; // too big for int ==> float ?>
One caution with floating-point numbers: Remember that they are only approximate values. Because of their limited precision, they are very close to the intended value but are not always the value you would like.
For example, the value 2.5 will often be represented internally as 2.4999999999, or something similar. Thus, the following code will often prove problematic:
<?php if (0.7 + 0.1 >= 0.8) echo "Hoooray!"; else echo "What???"; ?>
Code snippets such as these often print "What???", depending on the exact implementation of floating-point numbers.
The recommendation is to avoid comparing specific floating-point values. Instead, you should round them to the nearest integer value using round, or compare them against a range of values.
A string is a sequence of characters. In PHP, these characters are 8-bit values. This is convenient for many Western languages but proves a bit problematic when trying to work with systems using more complicated alphabets, such as Chinese. We will cover solutions for this in more detail in Chapter 6, "Strings and Characters of the World."
There are three ways to specify a string value.
Single-quoted strings are sequences of characters that begin and end with a single quote (').
<?php echo 'This is a single-quoted string.'; ?>
To include a single quote within a string, you simply put a backslash in front of it. This is called escaping the character.
<?php echo 'This is a single-quoted (\') string.'; ?>
If you actually want to print \' as output or if you want to end a string with a backslash character, then you need to escape the backslash one more time.
<?php echo 'This is a single-quoted string.'; echo '<br/>'; echo 'This is how to print a single quote: \' in a string.'; echo '<br/>'; echo 'And now to show a backslash in the output: [ \\\' ]'; echo '<br/>'; echo '\And now to terminate a string with a backslash\\'; echo '<br/>'; ?>
The previous script produces the following output:
This is a single-quoted string. This is how to print a single quote: ' in a string. And now to show a backslash in the output: [ \' ] \And now to terminate a string with a backslash\
No other escaping or expansion is supported. Therefore, in the previous code, \A just prints out the two characters.
Double-quoted strings are similar to single-quoted strings, except that the PHP language processor actually dissects them to find and replace special escape sequences and variables.
<?php echo "This is a double-quoted string."; ?>
In addition to the escape sequence \" required to insert a double quote within a double-quoted string, PHP understands the following escape sequences:
No other escape sequences are supported, and (in the case of single-quoted strings) non-matching sequences will simply print the backslash and the other character.
<?php echo "This is a rich \"\$\$\" double-quoted string."; echo "<br/>\n"; echo "This is a rich \042\x24\x24\042 double-quoted string."; echo "<br/>\n"; echo "This won't quite do what \n\n you expect it to!"; echo "<br/>\n"; echo "Neither likely will this."; echo "<br/>\n"; echo "\\ + A isn't a valid escape, so this will print \A"; ?>
The previous script produces the following output in a web browser:
This is a rich "$$" double-quoted string. This is a rich "$$" double-quoted string. This won't quite do what you expect it to! Neither likely will this. \ + A isn't a recognized escape, so this will print \A
Most of this should be intuitive, except for the third string, into which we have injected some newline characters (\n), or the fourth string, which spans multiple lines. The problem is that our output medium is HTML, which is a markup language that formats the output based on specially tagged instructions in the input stream. The actual HTML generated is more in line with what we would expect:
This is a rich "$$" double-quoted string.<br/> This is a rich "$$" double-quoted string.<br/> This won't quite do what you expect it to!<br/> Neither likely will this.<br/> \ + A isn't a recognized escape, so this will print \A
However, HTML ignores whitespace (spaces, Tab characters, and newlines) when processing its input for formatting. Thus, our new lines, which are not the explicit line break instruction like the <br/> tag, are simply ignored.
Both single-and double-quoted strings can span multiple lines, as in the fourth example shown previously. The newline characters are simply interpreted as part of the input string.
The third way to input strings in PHP script is to use the heredoc syntax, an innovation seen in languages such as Perl and Bourne Shell scripting. In this, a string begins with <<< and an identifier and continues until PHP sees an input line of text consisting only of the left-aligned (same) identifier and a semicolon character (;).
<?php echo <<<HTML <p align='center'> This is an example of text being input using the heredoc Notation in PHP. It is nice, because I can pretty much type <em>freely</em> without having to worry about how to fit it all into a double-quoted string. </p> HTML; ?>
Heredoc strings behave much like double-quoted strings, although you do not need to escape as many of the charactersnewline characters and tabs can be freely entered. In fact, you only need to worry about escaping $ characters, which we will discuss in "More on Entering Strings" in Chapter 2. Other escapes will be processed, but are not necessary.
There are two common pitfalls when using the heredoc notation relating to how the identifier is specified after the <<< delimiter and how the closing line is specified. Any whitespace in either of these locations causes the PHP processor to incorrectly identify the string value.
<?php echo <<<MOO... This is not going to work. MOO; echo <<<OINK Nor will this. OINK;... ?>
Assuming that the '...' in the previous entries are the number of whitespace characters, you get the following compiler error on the first heredoc:
Parse error: parse error, unexpected T_SL in /home/httpd/www/test.php on line 22
You receive the following error for the second heredoc:
Parse error: parse error, unexpected $end in c:\Inetpub\wwwroot\blah.php on line 48
Booleans are the simplest type in the PHP type system and express a binary valuetrUE or FALSE, YES or NO, 1 or 0. The value of a Boolean variable can be either trUE or FALSE. These two keywords are not case sensitive.
<?php $apple = TRUE; $orange = fAlSe; $cat = tRUe; $dog = False; ?>
If you try to print the value of a Boolean variable or expression, you see a 1 for TRUE and 0 for FALSE.
Many operators, which we will see in "Expressions and Operators" (in Chapter 2), evaluate to Boolean values. In "Type Conversions" (also in Chapter 2), we will look at how you can convert from other types to Boolean and vice versa, besides looking at some conversions that might not be intuitive.