Saturday, December 8, 2007

Operators and Functions

Operators and Functions

We've seen several places in PHP code where values are required: most commonly, we have been telling the echo command to print out a value. We've also used values in a few other places: on the right hand side of an assignment operation, as arguments to functions, and even inside curly brackets in a complex variable reference.

There are several ways of providing a value to PHP in any of these locations. Those things which PHP is able to interpret as values for use in these situations are called expressions, and we've met three types of expression already: literals, variables, and constants.

An expression is anything that can be treated as having a value. Literals have their literal value, variables refer to a stored value, and constants do the same. However, these aren't the only types of expression in PHP. PHP supports two expression types which are evaluated to determine the value they will take on: operations and function calls.

We've seen function calls used in this way:

    echo(gettype("Hello"));

The function call (gettype("Hello")) is evaluated to provide the piece of data ("string") which is passed to the echo command. It is an expression – it has a value. This function call can, as we've said, be used in any of the places where a variable or literal could be used. The following are therefore all valid:

    $a = gettype("Hello");
${gettype("Hello")} = "World";
echo(gettype(gettype("Hello")));

The first stores the string "string" in $a, the second stores the string "World" in the variable $string, and the third prints the result of calling gettype() on the value gettype() returns.

An operation is an expression containing an operator. In the following:

    echo(2 + 2);

2 + 2 is an operation, and it has the value 4. Operators are like shorthand functions. If there was a function that provided the functionality, you could get exactly the same effect as the above by writing:

    echo(add(2, 2));

The addition operator (+) is a binary operator: it operates on two values. Other binary operators include the greater-than operator (>), the string concatenation operator (.), and the assignment operator (=).

There are also unary operators, which operate on a single value. Examples are the increment operator (++), the Boolean NOT (!), and the casting operators we met earlier, such as (int).

There is also a ternary operator, which works on three values. It should be familiar to anyone who's used a C-like language. Since there's only one, it's often referred to simply as "the ternary operator". It's the conditional operator and is used to choose between two values, depending upon the value of a third. The expression:

    $a ? $b : $c

evaluates to the value in $b if $a evaluates to true, and to the value in $c if it evaluates to false:

    echo("INDEPENDENCEDAY is " . (defined("INDEPENDENCEDAY") ? "defined" :
"not defined"));

Here the string that is printed depends on the return value of defined().

Some operators expect their operands to be of a certain type. In these circumstances, PHP will perform the type-conversion necessary to allow the operation to be performed. We saw this above with the addition operator, which expects two numerical arguments, and which forced the conversion of a string to a number before performing the addition. Other operators expect strings, or booleans, and perform similar conversions.

We'll now take a look at some of the basic operations and functions PHP provides that can be performed on values of various types.

General Operations

The most important operators are the assignment, equality, and inequality operators. They can operate on values of any type, and are used everywhere.

The assignment operator, as we've seen, is the equals sign, =. The left hand argument must be an assignable entity – generally a variable reference. The right hand argument can be any expression. The result of performing the operation is that the variable on the left is assigned the value of the expression on the right. It's important to remember, however, that the assignment operation is itself an expression: it has a value. The value it takes on is the value of the right hand expression. This means you can do the following:


echo($a = "Hello");
$a = $b = $c = "Hello";

The first prints out the value "Hello", whilst also assigning it to $a. The second assigns the value "Hello" to $c, then assigns the same value to $b, and then assigns the same value to $a.

The equality operator is a double equals, ==. It takes any two expressions as arguments, and evaluates to Boolean true if the values are equal, and Boolean false otherwise. The inequality operator, !=, returns the opposite value:

    $a = 2;
echo($a == 2);

One word of warning when working with floating-point values in PHP: the double-precision floating-point arithmetic PHP uses is not always as precise as we would like. Take a look at the following PHP code:

       $a = 1.1;
$b = 0.4;
$c = $a - $b;
echo(($c == 0.7) ? "true" : "false");
?>

This puts the floating-point values 1.1 and 0.4 into two variables, and then performs a subtraction. 1.1 minus 0.4 should be 0.7. We test to see if this is the case using the ternary operator: the first argument is an equality operation which will return true if the two values are equal, and false otherwise. The ternary operator will, then return either "true" or "false" as a string accordingly.

What should happen is that the equality test will be passed, and the word "true" will be echoed out. Unfortunately, this isn't always the case. The precision of floating-point numbers is platform-dependent, but on a 32-bit computer running Windows, this program will print out "false". This is because the floating-point value is stored as a binary number, and is only an approximation of the decimal fractions we are trying to represent. Seven tenths doesn't translate well into halves, quarters, eighths, and sixteenths.

If you are performing critical calculations and want to be able to test fractional values for equality, you will need to use some of PHP's advanced mathematical functions. You should never test floating-point values for equality.

String Operations

PHP uses the period character (.) as a string concatenation operator. This is called the dot operator:

    $a = "Hello";
$b = "World";
$c = $a . $b;
echo($c);

There is also a shorthand operator, .=:

    $a .= $b

The above is the equivalent of:

    $a = $a . $b

Remember that if you want to include spaces or new lines between elements of a string, you'll have to do it manually. You can concatenate multiple strings together using the dot operator:

    $a = "Hello";
$b = "World";
$c = "" . $a . " " . $b . "";
echo($c);

String Functions

PHP offers a wide array of string handling functions. We'll only look at the most commonly used ones here; you can find a complete list of PHP functions in the PHP manual (http://www.php.net/docs.php). We won't cover regular expressions here, but they are by far the most powerful and flexible method of manipulating strings. These are covered in depth in Chapter 7.

substr()

    string substr(string string, int start [, int length]) 

The substr() function returns a section of the string. The first argument is the complete string, the second is the position within the string of the first character you want to be returned (counting from zero), while the third is the position of the last character of the string that you want to return. If you don't specify the third argument, then PHP will assume that you just wanted to include the rest of the string. Here are some examples of substr() in action:

    $String1 = substr("The cat sat on the mat", 4,3); // 'cat'
$String2 = substr("The frog sat on the log", 0,1); // 'T'
$String3 = substr("The aardvark sat in the dark", 17); // 'in the dark'

strpos()

    int strpos(string haystack, string needle [, int offset]) 

strpos() provides the opposite functionality to the substr() function. You supply it with a subsection of a string and it returns the first place within the string that the subsection can be found (if it can be found at all).

You supply the string you wish to search first, the string you are hoping to find as the second argument, and lastly there is an optional argument which allows you to specify a position within the string to start looking from. Some examples of strpos():


$String1 = strpos("The cat sat on the mat", "cat"); // Returns '4'
$String2 = strpos("rhubarbrhubarbrhubarb", "rhubarb", 6); // Returns '7'

htmspecialchars()

    string htmlspecialchars(string string [, int quote_style
[, string charset]])

The htmlspecialchars() function is a useful little function that searches a string for certain characters which need special representation in HTML and turns them into their HTML equivalents. This function will take the following five characters and translate them into their HTML code:

  • & becomes &

  • " becomes "

  • < becomes <

  • > becomes >

The second argument takes one of two constants as an argument: ENT_QUOTES or ENT_NOQUOTES. You use the former if you wish to translate quotes and the latter if you don't. The third argument takes a string representing the character set to be used in conversion. The default is ISO-8859-1.

An example of htmlspecialchars() in action could be as follows:

    echo(htmlspecialchars("

The cat sat on the mat

",
ent_quotes));

This outputs:

    <P class='class1'>The cat sat on the mat</P>

which a web browser will use to reproduce the original characters. Useful if you want to output HTML source-code for display in a web browser.

trim()

The trim() function is straightforward: it takes one argument, a string, and removes any preceding or trailing space characters:

    $String1 = trim("   a lot of white space     "); // 'a lot of white space'

Note that you can't use trim() like this to simply trim the contents of a variable:

    $a = "  a lot of white space     ";
trim($a);

Instead, to achieve the desired effect, you should use:

    $a = trim($a);

chr() and ord()

The chr() function takes the ASCII code of a character as an argument, and returns the actual character. The ord() function does the opposite:

    echo(chr(64));   // displays '@'
echo(ord('@')); // displays '64'

strlen()

The strlen() function takes one argument, a string, and returns the length of the string in characters, as an integer. For example:

    $String1 = strlen("one"); // '3'
$String2 = strlen("the cat sat on the mat"); // '22'

printf() and sprintf()

    int printf(string format [, mixed args...])
string sprintf(string format [, mixed args...])

The printf() and sprintf() functions are two related functions that provide rather more complex functionality than the other string handling functions we have considered. They both look after the process of formatting numbers and including them in a string, and provide functionality such as returning a date in the format mm/dd/yyyy or a currency value to 2 decimal places. The sprintf() function performs the requested formatting and returns a string, while the printf() function performs the same task, but echoes the result directly to the output destination – be that the browser or console.

Conversion Specifiers

The format argument of printf()/sprintf() is a string, containing certain special characters which will be used to format the data provided in the arguments list. These special characters are called conversion specifications. Normal characters, which will appear in the formatted string unchanged, are called directives. You need to provide one argument in the list for each conversion specification which appears in the format string.

If the format contains two conversion specifications, then you should provide two arguments, and they will be formatted according to the specification and inserted into the string. They'll be placed in the location where the conversion specification appears.

A conversion specification is a percent character (%), followed by up to five specifiers, in the following order:

  • Padding Specifier
    This is used to specify a character which can be used to pad the string out to a particular size. If omitted, a space is assumed. This only has any effect if a minimum width specifier is added.

  • Alignment Specifier
    Normally, padding is added to the left of a string to extend it to the minimum width, leading to the string being right-justified, but if you add the hyphen character () then the string is left-justified.

  • Minimum Width Specifier
    This is an integer value which specifies the minimum size of the formatted string. If the string supplied is smaller than that, then the string is padded out using either a space, or the character indicated in the padding specifier, if supplied.

  • Precision Specifier
    When using fractional/floating-point numbers, you can specify how many decimal places the number should be displayed with. The specifier is written as a decimal point, followed by an integer specifying the number of decimal places which will be displayed. This specifier can also be used to format strings, and it specifies the maximum number of characters from a supplied string which will be included.

  • Type Specifier
    The type specifier is used to indicate the type of data which will be supplied in the argument, and, in the case of an integer, which mode it should be displayed in. It can be one of the following characters:

    • b – an integer presented as a binary number

    • c – an integer presented as the character with that ASCII value

    • d – an integer presented as a decimal number

    • f – a floating-point value presented as a decimal fraction (with a decimal point)

    • o – an integer presented as an octal number

    • s – a string

    • x – an integer presented as a hexadecimal number (with lowercase letters)

    • X – an integer presented as a hexadecimal number (with uppercase letters)

In addition, to include a literal percentage character in a formatted string, you must write a double percent (%%).

Let's have a look at some examples of the sprintf()/printf() functions now. We mentioned that they could be used to format dates or currencies, so let's look at some examples of this now, starting with a date:

    $day = 1;
$month = 2;
$year = 2001;
printf("%02d/%02d/%04d", $month, $day, $year);

This produces the following output:

    01/02/2001

The format includes three conversion specifications, one for the month, one for the day, and one for the year. We are formatting the month and day as two-digit integers, and the year as a four-digit integer. In order to do this, we need to specify that the integers should be padded out to a minimum length, with zeroes on the left. So, the conversion specification for the month, for example, looks like this:

    %02d

The first character is a zero, and is the padding specifier. There is no alignment specifier, because we want the padding to be added to the beginning of the number. We'll add a minimum width specifier, which is 2. We're formatting an integer, so we don't need a precision specifier. Then the last character is the type specifier, d, which tells the printf() function to format the number as a decimal integer.

The second example formats for English currency:

    $Value2 = 23;
$Value2 = sprintf("£%.2f", $Value2);

echo($Value2);

and would produce the following:

    £23.00

This floating-point conversion specifier, %.2f, simply tells the formatter to omit all but the first two digits after the decimal point. No padding or minimum length is specified, so the number to the left of the decimal point can be any length.

Numerical Operations

The basic numerical operators that you can use in PHP to perform mathematical operations should be familiar to anybody who has done math at school. They are as follows:

Operator

Operation

+

The addition operator

*

The multiplication operator

The subtraction operator

/

The division operator

%

The modulus operator (works out the remainder left by division) e.g. 8 % 5 is 3

In most cases, if the arguments are both integers, they will return an integer, but if you include a floating-point value, they will return a floating-point value – even if the result has no fractional component. 1.5 plus 1.5 is 3.0, not 3.

There are assignment variants of all of these operators. To save you from having to write $a = $a + $b, you can use the shorthand $a += $b. Similar versions exist for all of the above operators.

For addition and subtraction, there are two other shorthand operators: the increment (++) and decrement (−− ) operators. There is a slight subtlety in the use of these unary operators, depending on whether you see them before or after the operand. This doesn't matter much when you use them as below, simply to increase the value of a variable. These two code snippets are identical:

    $a = 1;
$a++;


$a = 1;
++$a;

The difference happens when you look at the value returned by the increment operation in each case. Remember we said all operations are actually expressions – they return a value. The result of the following will be that the number 1 gets sent as output:


$a = 1;
echo($a++);

This is because a postpended increment operator returns the value of its operand, and then increases it by one. On the other hand, this code:

    $a = 1;
echo(++$a);

will print out 2. The prepended increment operator performs the increment first, and then returns the resulting value. The decrement operator acts in the same way.

Bitwise Operators

Another set of operators also work with numerical values – bitwise operators. These operate on the binary data underlying integer values as a string of bits. There are bitwise AND (&), OR (|), XOR (^), NOT (~), shift left (<<), and shift right (>>) operators. You can use these to create sets of Boolean flags. Here is an example of a set of flags, which signify user permissions:

       define(CREATE_RECORDS, 1);
define(DELETE_RECORDS, 2);
define(ALTER_RECORDS, 4);
define(ADMINISTRATOR, 8);

$user_permissions = CREATE_RECORDS | ALTER_RECORDS;

echo(($user_permissions & CREATE_RECORDS) ? "user can create records
" : "");
echo(($user_permissions & DELETE_RECORDS) ? "user can delete records
" : "");
echo(($user_permissions & ALTER_RECORDS) ? "user can alter records
" : "");
echo(($user_permissions & ADMINISTRATOR) ? "user is an administrator
": "");
?>

We create a set of constants whose values are all powers of two – the integers 1, 2, 4, and 8. In binary, these are 0001, 0010, 0100, and 1000. Then we build a set of user permissions out of these constants using the binary OR operator. The value of the $user_permissions variable is actually set to 1 OR 4, which is in fact 5: 0101. The flags for "create records" and "alter records'"have been set.

Then we test the user's permissions against each of the constants using the binary AND operator. If the user permission flag for one of the values is set, then ANDing the values together will create a non-zero value. If the flag isn't set, the result of the AND operation will be zero. If the result is zero, nothing is printed – if it's non-zero, the relevant string is output.

Like the arithmetic operators, there is an assignment version of the AND, OR, and XOR operators. For an example, add the following line to the program:

       define(CREATE_RECORDS, 1);
define(DELETE_RECORDS, 2);
define(ALTER_RECORDS, 4);
define(ADMINISTRATOR, 8);
$user_permissions = CREATE_RECORDS | ALTER_RECORDS;
$user_permissions |= DELETE_RECORDS;

echo(($user_permissions & CREATE_RECORDS) ? "user can create records
" : "");
echo(($user_permissions & DELETE_RECORDS) ? "user can delete records
" : "");
echo(($user_permissions & ALTER_RECORDS) ? "user can alter records
" : "");
echo(($user_permissions & ADMINISTRATOR) ? "user is an administrator
": "");
?>

The shift left and shift right operators shift the bits of the specified integer left or right by the amount specified. Each step is equivalent to multiplying or dividing by two, respectively:

    define(TWO, 2);
define(FOUR, 4);

echo(TWO << FOUR); // 32
echo(FOUR >> TWO); // 1

Comparison Operators

The final set of operators used in conjunction with numbers is the comparison operators: less-than (<), less-than-or-equal (<=), greater-than (>), and greater-than-or-equal (>=). All of these compare the two values they are given and return either true or false.

Operator Precedence

These simple mathematical operations begin to become more complex when combined. The following statement is, on the face of it, quite simple, but also ambiguous:

    $sum = 5 + 3 * 6;

If you calculate it in the strict order as it appears, you'll end up with 48. However, following the mathematical order of precedence, you'll come up with the total 23. Clearly you need C-style rules to sort out operation order. PHP follows the ordering below when evaluating an expression which contains more than one operator:

Numerical Operators

++, , ~, casting operators

*, /, %

+,

<, <=, >, >=

==, !=

&

^

|

As in mathematics, PHP uses parentheses to override these rules of precedence. So, to get 48:

    $Sum = (5+3)*6;

Logical Operators

The logical operators are used to test Boolean conditions. PHP has operators for the four main Boolean conditions: AND (and or &&), OR (or or ||), NOT (!), and XOR (xor). AND and OR have two different operators because they have different precedences.

Here is an example of the logical operators in action:

    if (file_exists("travel.xml") && is_readable("travel.xml")) {
fopen("travel.xml", r);
echo("travel.xml opened");
} else {
echo("travel.xml not opened");
}

This code snippet checks to see that travel.xml exists AND that travel.xml is readable before it is opened for reading.

Operator Precedence

The logical operators also have a precedence associated with them:

Logical Operators

or

xor

and

||

&&

!

Data Types

Data Types

While PHP is very flexible with variables and allows you to treat them as text values one moment and numbers the next, it does have a set of data types that it assigns when dealing with a variable. The eight types are as follows:

  • string

  • integer

  • double

  • array

  • boolean

  • object

  • resource

  • unknown

double is PHP's word for a floating-point value; it stores floating-point values with "double precision". Since PHP doesn't have "single precision" floating-point numbers, this distinction isn't really significant.

You can check on what type PHP has assigned to a variable by using the gettype() function:

       $Variable = "This is some text";
echo(gettype($Variable));
?>

This will print out string.

You can also use the related function settype() to explicitly set the type. It requires the variable name followed by the type you wish to set it to:

    $Variable = "2";
settype($Change, integer);
echo(gettype($Change));
echo($Change);

Casting

PHP also has casting operators, which allow you to tell PHP to treat a value of one type as if it were of another type. The casting operators are the name of the type to which you want to cast the data, enclosed in parentheses:

  • (string)

  • (integer)

  • (double)

  • (boolean)

There are also abbreviated versions of some of these operators:

  • (int)

  • (bool)

They are used as follows:

       $a = "123.456";
echo((int)$a);
?>

This prints out 123 because PHP has converted the string value, 123.456, into a whole integer.

PHP also has some interesting behavior when it performs conversions. Take a look at the following code:

    $Change = "2 Coffee Candies";
settype($Change, integer);
echo(gettype($Change));
echo($Change);

Instead of causing an error, this program will actually display integer and 2. For the text to become an integer, it has to lose the extraneous information that can't be turned into a number, but PHP finds the number at the start of the string and uses that. You can procure this explicit type-conversion behavior without settype():

    $Variable1 = 3;
$Variable2 = "2 Coffee Candies";
$SumTotal = $Variable1 + $Variable2;

The result of this sum would be 5 because PHP recognizes the addition operation, and understands that's your intention. It performs an integer conversion on $Variable2 and then adds the contents of the two variables together. In other programming languages this would quite likely cause an error, but because of PHP's weak typing, you're allowed to get away with it.

To understand properly how PHP makes these decisions, let's look at how it treats operators.

Constants

Constants

Constants are containers just like variables for data, but once you've assigned a value to one, you can't change it in any way. Constants are defined using a separate method to variables in PHP (in some languages constants are declared in the same way, but using a keyword which defines them to be constant). Constants are created using the define() function in PHP:

    define("INDEPENDENCEDAY", "4th July");

Whenever you wish to reference it within the body of code, you can do so simply by using its name:

    echo(INDEPENDENCEDAY);

By convention, constants are given all uppercase names, although this is only a convention, and you're free to choose any name that conforms to the variable naming rules.

PHP constants are essentially meant to function in a similar way to C pre-processor #defines: you can declare them in one location, and execute different code later on depending on whether the constant was defined, or what value it was defined as. This is tested using the defined() function:

    if (defined("INDEPENDENCEDAY")) {
echo("INDEPENDENCEDAY is defined");
} else {
echo("INDEPENDENCEDAY is not defined");
}

Variables

Variables

A variable in PHP, like in most other languages, is simply a container for some data. You can give your variables names, put data into them, and then refer back to them at a later point in your program to access the stored data.

PHP identifies variables using the dollar sign ($). The name for a variable will always begin with this character whenever you refer to it. After the dollar sign, your variable name can consist of any number of alphanumeric characters and underscores, although the first character cannot be a number or an underscore. So, the following are all valid variable names:

    $a
$a2
$my_name
$height_in_metres_above_sea_level

The other thing to remember is that PHP variable names (unlike keywords) are case sensitive, so all of the following refer to different variables:

    $my_name
$MY_NAME
$My_Name

PHP doesn't require you to declare variables before you use them, or to tell it what kind of data you plan to store in the variable. The same variable can, over the course of a program, store many different data types. A variable is created as soon as you assign it, and then exists for as long as the program is executing. In the case of a web page, that means it exists until the request has been completed.


Note

The exceptions to this are functions, which have their own variable scope.

Assignment

To assign a value to a variable, you use an assignment statement, in this form:

    $variable_name = expression;

We'll look at expressions in more detail in a moment. For now, let's assume that the expression is either a literal, or another variable. That means that the following will all work:

       $a = "Hello";
$b = 123;
$c = $a;
?>

Now that we've got a variable, we can use it in the same way as we used literals before:

       $a = "Hello";
echo($a);
?>

As we said, when we enclose a string in double quotes, PHP looks through it for variable names and substitutes in values. Now we can see how that might work:

       $a = "Hello";
echo("$a World!");
?>

Now, even though the variable reference is inside a string literal, it is still evaluated, and the output is:

    Hello World!

Note that it is evaluated at the time that the literal is interpreted. In the following example:

       $a = "Hello";
$b = "$a World!";
$a = "Goodbye";
echo($b);
?>

The output is still Hello World! because the variable substitution takes place at the point that the literal is interpreted into a string and stored in the variable $b. The subsequent change to $a doesn't affect $b.

Reference

PHP also provides another way of referencing variables. A variable reference of the form:

    ${expression}

refers to the variable whose name is the result of evaluating the expression. So, if the expression is a string literal, like this:

    ${"my_name"}

the variable referred to is $my_name. If the variable $a contained the string "name", then:

    ${"my_$a"}

would also refer to the variable $my_name – the string is evaluated, as before, to the string "my_name", and this is used to refer to the variable. Now, if the variable $a were to contain "my_name", then:

    ${$a}

would also refer to $my_name. However, PHP also provides an even shorter syntax for this special case. If the name of the variable is simply contained in another variable, like this, then you can use this notation:

    $$a

to refer to the variable $my_name.

These substitutions will work anywhere where a variable reference is required, including on the left hand side of assignment statements, and within double-quoted strings.

Literals

Literals


We've used a lot of literals already in our examples up to this point. PHP understands three basic kinds of literal: textual literals (strings), numeric literals (integers and floating-point numbers), and Boolean literals (true and false).

Textual Literals

You can specify strings in one of three ways: double quotes, single quotes, or ‘here document’ syntax.

When you enclose a string literal with double quotes, PHP parses it looking for several types of special character. It looks for the names of variables and substitutes their value in the process. It looks for backslash characters, and reads the following character in order to determine what to replace the two-character code with. Possible values are:

Value

Meaning

n

Linefeed (LF)

r

Carriage return (CR)

t

Tab

\

Backslash

$

Dollar sign

"

Double-quote

An octal number of up to three digits

The character whose ASCII code corresponds to the octal number

x followed by a hexadecimal number of up to two digits

The character whose ASCII code corresponds to the hexadecimal number

So, the following code:

  

produces:

    This text goes
across several
lines
"and this quotation is indented"

It's worth noting that when you view the output of that PHP script in a web browser, you get this:

This text goes across several lines "and this quotation is indented"

Browsers ignore line breaks and other whitespace characters (tabs, spaces) when rendering. To tell a browser to include a line break you have to use the
(or XHTML
) tag. Alternatively, you can use the nl2br() function which inserts HTML line breaks before all newline characters in a string.

When you use single quotes, the only escape codes which work are \' and \\, for a single quote character and a backslash respectively. Every other character is reproduced literally. So, if we simply replace the quotation marks in our previous example with single quotes:

  

The output is:

    This text goes\nacross several\nlines\n\t\"and this quotation is indented\"

As you can see, all of the characters are reproduced literally, including the backslashes.

Here Documents

Here documents are a way of including large blocks of formatted text in a string instead of using multiple echo statements. A here document is used like this:

    $hereText=<<

After the <<< characters, which tell PHP that a here document is about to begin, we supply a final delimiter. This can be any sequence of alphanumeric characters and/or underscores, although it must not begin with a number or an underscore. The text of the here document then begins on the next line. To tell PHP that it has reached the end of the here document, we simply include a line beginning with the final delimiter which we declared at the start.

The text within a here document is interpreted according to the same substitution rules as a double-quoted string, so you can include variables and escape characters.

Numeric Literals

PHP understands both integer and floating-point numbers. Integers can be specified in decimal, octal, or hexadecimal notation:

  

Hexadecimal numbers are identified by the preceding zero followed by an x. Octal numbers simply begin with a zero.

The echo command always outputs integers using decimal notation, even if they were specified as hex or octal, so the above code writes out the number 255 three times.

You can declare negative integers by preceding any of these notations with a minus sign. To declare floating-point numbers, you can use either decimal point or exponential notation. The following are all valid:

  

The e or E character in the last two versions is regular "exponent".

Boolean Literals

PHP also understands the words true and false, and you can use them in certain operations which require a Boolean value. Like all PHP keywords, these are case insensitive, and you can use true, TRUE, and True interchangeably.

Statements

Statements

Within the PHP delimiters, you can write any number of statements. There are two types of statement: single line, and multi-line.

Single line statements must end with a semi-colon, unless they are the last statement before the closing delimiter of a PHP block, when the semi-colon can be omitted. So, the following are both legal:

    two plus two is 

two plus two is

Single line statements may also contain, paradoxically, line breaks. This is because PHP doesn't assume a statement is finished until it encounters a semi-colon, and line breaks are just considered as whitespace, which, in most places within PHP delimiters, PHP ignores. Similarly, there is no requirement that a semi-colon be followed by a line break before the next statement begins. So, the following two sets of statements are exactly equivalent:

    

Multi-line statements make use of a construct called a code block. A code block contains multiple PHP statements, enclosed in curly brackets ({ }):

    {
echo("hello");
echo(2 + 2);
}

Although you can use code blocks just like this in your PHP code, they don't have any effect on the code (in particular, unlike in C or Java, they have no effect on variable scope). Code blocks are only of use when used in conjunction with control structures, such as loops, or if statements:

    if (3 > 2) {
echo("hello");
echo(2 + 2);
}

In this case, we have a multi-line statement. The statement consists of the control structure and the code block. Since it is clear where the statement ends, there is no semi-colon on the end of the statement – only on the end of the statements contained within the code block.

Note that it is also possible to ‘un-escape’ from PHP within a code block (but not within a single line statement), provided that you subsequently escape back to PHP and finish off the block, as follows:

     2) {
echo("hello");
?>
This line is not interpreted as PHP code, and is only printed out if the code
block is executed.


Comments

PHP provides several methods for including comments in code. The simplest is to insert a double slash, which tells PHP to ignore everything up to the next line break:

   

You can do the same with a hash sign:

   

Of course, you can also insert comments in other places – not just after the end of a statement. You can add comments anywhere where PHP lets you add whitespace. The following are all legal:

   

PHP also supports C++/Java style multi-line comments, using the /* */ delimiters:

    $Calculation = (($x/$y) * 7.5) / $z ;
/* The above calculation takes the price
differential, x and divides it by the
number of customers, y. We multiply this
figure by the current interest rate (7.5)
and then divide it by the decimal figure
stored in z */

It's worth remembering that these styles of comment will only work within the PHP code delimiters. If PHP encounters these markers outside the delimiters, they'll be treated just like any other text, and will be included in the output. You can use this to your advantage when using PHP for web scripting, by including HTML comments in the output, like this:




// this PHP comment will show up in the browser - oops


This can be useful for debugging or for making generated HTML source code more understandable.

php Programs

PHP Programs

PHP programs are stored in standard text files, which you can create using any text editor (note that Macintosh text editors sometimes add line break characters which PHP has trouble understanding, so you should look for an option in such editors to save files with ‘UNIX-style linebreaks’). Normally, you will need to save the file with the file extension .php for it to be executed by a web server, although the extension can usually be configured to anything you like. Here is an example from Apache's httpd.conf file, where we have created a .prophp4 extension:

    AddType application/x-httpd-php .prophp4

Alternatively, if you are using PHP to write console programs, the file extension isn't important.

File Basics

PHP programs are executed in one of two ways: by a web server, or as a console program. PHP programs can be made available via a web server which has been configured to support PHP by adding them to the web server's directory structure, where you would normally locate HTML files. They are accessed from a web browser in exactly the same way as static web pages. When a browser requests a page ending in the .php extension the web server runs the program through the PHP engine.

When the PHP engine begins to execute the script, its default behavior is to output the contents of the file, unaltered. This output will either go to the browser that requested the page, or the console when executing as a script.

You can simply take an ordinary HTML page, rename it so it has a .php extension, and PHP will process it, but perform no work on it at all.

In order to include PHP instructions in the file, we need to ‘escape’ from this standard output mode, into PHP. This is done by enclosing PHP instructions in delimiters.

SGML processing instruction:

       ...
?>

XML processing instruction:

       ...
?>

HTML editor-friendly script-style:

    

ASP style, for editors that understand ASP tags but not PHP tags:

    <%
...
%>

We'll be using the XML style throughout this book, but there is no functional difference between any of these sets of delimiters.

One code style which you may come across, although we won't be using it much because it can cause confusion, is the following:

    
<%= ... %>

These abbreviated tags execute the enclosed single PHP expression, and replace the entire tag with the result. The following, though debatable practice, is an example:

    two plus two is 

The output of this would be:

    two plus two is 4

Most of the time, instead of using this style of delimiter to output values from PHP code, we'll use the echo command, as follows:

    two plus two is 

The echo command is one of the most common ways to add text to the output stream from within PHP delimiters. Most of the operations we will perform within PHP code blocks don't directly lead to any output at all, and when we want to add text which we have generated inside our program, we'll use echo to do it. We can use echo to print out text, numbers, or HTML markup. Really, anything that would normally be included in a web page. The crucial thing is that PHP allows us to perform all kinds of operations to determine exactly what output we should produce.