2.4 Functions

A function is another concept that programming derived from mathematics. Some programming functions are direct implementations of common mathematical functions, such as sines and other trigonometric functions. (Naturally, these are not used much in PHP.) But you are sure to use functions related to strings, dates, and other everyday objects in your code. PHP has a large number of useful functions built in, and you can define your own functions as we describe later in this chapter.

Functions are called in PHP scripts and can often be used as expressions. For instance, the following example uses the strtoupper( ) function to change a string to uppercase:

$var = "A string";

print strtoupper($var); // prints "A STRING"

A function is followed by parentheses, which can contain zero or more parameters. This function accepts just one parameter. It can be summarized as follows:

string strtoupper(string subject)

The previous statement is called a prototype and is very useful for introducing functions. Prototypes are used throughout PHP documentation, and the following chapters of this book, when a function is described. The first word indicates what is returned by the function: in this case, its output is a string. The name of the function follows, and then a list of parameters within parentheses. Each parameter is described by a type and a parameter name?strtoupper( ) is defined with a single string parameter named subject. Names allow us to distinguish multiple parameters when we describe the function.

Prototypes use brackets to indicate that function parameters that are optional. Consider the following prototype for the date( ) function:

string date(string format [, integer timestamp])

The date( ) function returns the current date and time as a string where the format is specified by the parameter format. The optional integer parameter timestamp allows non-current dates and times to be formatted. We discuss the date( ) function and timestamps in the next chapter.

When there is more that one optional parameter, then the parameters are shown in nested brackets:

string x(string p1 [, integer p2 [, integer p3]])

The fictional function x( ) must be called with at least p1, but optionally p2 and p3. The nesting of brackets indicates that parameter p3 can't be included without p2.

Some functions allow an unspecified number of parameters; these are indicated with three periods:

string y(string p1 , ...)