PHP Functions

PHP comes with hundreds of ready-made, built-in functions, making it a very rich language. To use a function, call it by name. For example, you can see the print function in action here:

print("print is a pseudo-function");

The parentheses tell PHP that you’re referring to a function. Otherwise, it thinks you’re referring to a constant. You may see a warning such as this:

Notice: Use of undefined constant fname – assumed ‘fname’ followed by the text string fname, under the assumption that you must have wanted to put a literal string in your code. (Things are even more confusing if there is actually a constant named fname, in which case PHP uses its value.)

Strictly speaking, print is a pseudo-function, commonly called a
construct. The difference is that you can omit the parentheses, as

print “print doesn’t require parentheses”;

You do have to put parentheses after any other functions you call,
even if they’re empty (i.e., if you’re not passing any argument to the

Functions can take any number of arguments, including zero. For example, phpinfo, as shown here, displays lots of information about the current installation of PHP and
requires no argument (the result of calling this function can be seen in Figure 5-1):


The phpinfo function is extremely useful for obtaining information about your current PHP installation, but that information could also be very useful to potential hackers. Therefore, never leave a call to this function in any web-ready code.

php Function
Figure 5-1. The output of PHP’s built-in phpinfo function

Some of the built-in functions that use one or more arguments appear in Example 5-1.

Example 5-1. Three string functions
echo strrev(" .dlrow olleH"); // Reverse string
echo str_repeat("Hip ", 2); // Repeat string
echo strtoupper("hooray!"); // String to uppercase

This example uses three string functions to output the following text:

Hello world. Hip Hip HOORAY!

As you can see, the strrev function reversed the order of characters in the string, str_repeat repeated the string “Hip ” twice (as required by a second argument), and strtoupper converted “hooray!” to uppercase.


Defining a Function

The general syntax for a function is:

function function_name([parameter [, ...]])
// Statements


function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");

I’ll explain all the square brackets, in case you find them confusing. The first line of the syntax indicates that:
• A definition starts with the word function.
• A name follows, which must start with a letter or underscore, followed by any number of letters, numbers, or underscores.
• The parentheses are required.
• One or more parameters, separated by commas, are optional.

Function names are case-insensitive, so all of the following strings can refer to the print function: PRINT, Print, and PrInT.

The opening curly brace starts the statements that will execute when you call the function; a matching curly brace must close it. These statements may include one or more return statements, which force the function to cease execution and return to the calling code. If a value is attached to the return statement, the calling code can retrieve it, as we’ll see next.

Returning a Value

Let’s take a look at a simple function to convert a person’s full name to lowercase and
then capitalize the first letter of each name. We’ve already seen an example of PHP’s built-in strtoupper function in Example 5-1. For our current function, we’ll use its counterpart, strtolower:

$lowered = strtolower("aNY # of Letters and Punctuation you WANT");echo $lowered;

The output of this experiment is:

any # of letters and punctuation you want

We don’t want names all lowercase, though; we want the first letter of each name capitalized. (We’re not going to deal with subtle cases such as Mary-Ann or Jo-En-Lai for this example.) Luckily, PHP also provides a ucfirst function that sets the first character of a string to uppercase:

$ucfixed = ucfirst("any # of letters and punctuation you want");echo $ucfixed;

The output is:

Any # of letters and punctuation you want

Now we can do our first bit of program design: to get a word with its initial letter capitalized, we call strtolower on a string first, and then ucfirst. The way to do this is to nest a call to strtolower within ucfirst. Let’s see why, because it’s important to understand the order in which code is evaluated.

If you make a simple call to the print function:


The expression 5-8 is evaluated first, and the output is -3. (As you saw in the previous
chapter, PHP converts the result to a string in order to display it.) If the expression
contains a function, that function is evaluated first as well:


PHP is doing several things in executing that short statement:
1. Evaluate 5-8 to produce -3.
2. Use the abs function to turn -3 into 3.
3. Convert the result to a string and output it using the print function.
It all works, because PHP evaluates each element from the inside out. The same procedure is in operation when we call the following:

ucfirst(strtolower("aNY # of Letters and Punctuation you WANT"))

PHP passes our string to strtolower and then to ucfirst, producing (as we’ve already
seen when we played with the functions separately):

Any # of letters and punctuation you want Now let’s define a function (shown in Example 5-2) that takes three names and makes each one lowercase with an initial capital letter.

Example 5-2. Cleaning up a full name
 echo fix_names("WILLIAM", "henry", "gatES");
 function fix_names($n1, $n2, $n3)
 $n1 = ucfirst(strtolower($n1));
 $n2 = ucfirst(strtolower($n2));
 $n3 = ucfirst(strtolower($n3));
 return $n1 . " " . $n2 . " " . $n3;


You may well find yourself writing this type of code, because users often leave their Caps Lock key on, accidentally insert capital letters in the wrong places, and even forget capitals altogether.

The output from this example is:

William Henry Gates


Returning an Array

We just saw a function returning a single value. There are also ways of getting multiple
values from a function. The first method is to return them within an array. As you saw in Chapter 3, an array is like a bunch of variables stuck together in a row. Example 5-3 shows how you can use an array to return function values.

Example 5-3. Returning multiple values in an array
$names = fix_names("WILLIAM", "henry", "gatES");
echo $names[0] . " " . $names[1] . " " . $names[2];
function fix_names($n1, $n2, $n3)
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));
return array($n1, $n2, $n3);

This method has the benefit of keeping all three names separate, rather than concate‐
nating them into a single string, so you can refer to any user simply by first or last name, without having to extract either name from the returned string.

Passing by Reference

In PHP, prefacing a variable with the & symbol tells the parser to pass a reference to the variable’s value, not the value itself. This concept can be hard to get your head around, so let’s go back to the matchbox metaphor from Chapter 3. Imagine that, instead of taking a piece of paper out of a matchbox, reading it, copying it to another piece of paper, putting the original back, and passing the copy to a function (phew!), you simply attach a piece of thread to the original piece of paper and pass one end of it to the function (see Figure 5-2).

Figure 5-2. Imagining a reference as a thread attached to a variable


Now the function can follow the thread to find the data to be accessed. This avoids all
the overhead of creating a copy of the variable just for the function’s use. What’s more, the function can now modify the variable’s value.
This means you can rewrite Example 5-3 to pass references to all the parameters, and
then the function can modify these directly (see Example 5-4).

Example 5-4. Returning values from a function by reference
$a1 = "WILLIAM";
$a2 = "henry";
$a3 = "gatES";
echo $a1 . " " . $a2 . " " . $a3 . "<br>";
fix_names($a1, $a2, $a3);
echo $a1 . " " . $a2 . " " . $a3;
function fix_names(&$n1, &$n2, &$n3)
$n1 = ucfirst(strtolower($n1));
$n2 = ucfirst(strtolower($n2));
$n3 = ucfirst(strtolower($n3));

Rather than passing strings directly to the function, you first assign them to variables
and print them out to see their “before” values. Then you call the function as before,
but put an & symbol in front of each parameter, which tells PHP to pass the variables’
references only.

Now the variables $n1, $n2, and $n3 are attached to “threads” that lead to the values of $a1, $a2, and $a3. In other words, there is one group of values, but two sets of variable names are allowed to access them.
Therefore, the function fix_names only has to assign new values to $n1, $n2, and $n3
to update the values of $a1, $a2, and $a3.

The output from this code is:

WILLIAM henry gatES

William Henry Gates


As you see, both of the echo statements use only the values of $a1, $a2, and $a3.

Be careful when passing values by reference. If you need to keep the original values, make copies of your variables and then pass the copies by reference.

Returning Global Variables

You can also give a function access to an externally created variable by declaring it a global variable from within the function. The global keyword followed by the variable name gives every part of your code full access to it (see Example 5-5).

Example 5-5. Returning values in global variables
$a1 = "WILLIAM";
$a2 = "henry";
$a3 = "gatES";
echo $a1 . " " . $a2 . " " . $a3 . "<br>";
echo $a1 . " " . $a2 . " " . $a3;
function fix_names()
global $a1; $a1 = ucfirst(strtolower($a1));
global $a2; $a2 = ucfirst(strtolower($a2));
global $a3; $a3 = ucfirst(strtolower($a3));

Now you don’t have to pass parameters to the function, and it doesn’t have to accept
them. Once declared, these variables remain global and available to the rest of your
program, including its functions.


In order to retain as much local scope as possible, you should try
returning arrays or using variables by association. Otherwise, you will
begin to lose some of the benefits of functions

Recap of Variable Scope

A quick reminder of what you know from Chapter 3:
• Local variables are accessible just from the part of code where you define them. If
they’re outside of a function, they can be accessed by all code outside of functions,
classes, and so on. If a variable is inside a function, only that function can access
the variable, and its value is lost when the function returns.
• Global variables are accessible from all parts of your code.
• Static variables are accessible only within the function that declared them but retain
their value over multiple calls