. 26
( 132 .)


The first time through, $i is assigned the value of 0, so the first element in the
array will be printed. The next time and each subsequent time through, $i will be
incremented by one. The loop will end as soon as $i is equal to the length of the
array (which is 4). Remember that the elements in the array start at 0, so the last
element in the above array is $myarray[3].
You can also leave any of the three expressions in the for loop empty. If you
leave the second expression empty, the if condition will evaluate to true, and you
will need to make sure that your loop will eventually hit a break statement (we dis-
cuss break in the section “break” later in this chapter).

Running the following code would be very bad: It would run indefinitely,
using up your memory and CPU.You™d have to kill the Web server to get this
script to stop. It could bring your entire machine down.
for ($i = 0;; $i++)
echo “$I <br>\n”;

The foreach structure is used exclusively with arrays. You can use it in place of
list() = each() on most occasions. This structure will work from the beginning
to the end of an array, assigning each element to a scalar variable (a variable that
has only one value, such as an integer or a Boolean value, as opposed to a multi-
element array or complex object) that you indicate with the word as. The following
prints all the values in the array $names_array:

$names_array = array(“jay”, “brad”, “ernie”, “bert”);
foreach ($names_array as $first_name)
echo $first_name;

If you are working with an associative array, you will likely need to access both
the key and the value of every array element. The following syntax will enable you
to do this:

$jay_info = array (“fname” => “jay”, “lname” => “greenspan”, “hobby”
Chapter 5: Control Structures 131

foreach ($jay_info as $key => $value)
echo “<b>$key:</b> $value <br>\n”;

Unlike list() = each(), foreach() does not require you to reset the array
afterwards. It works with a temporary copy of the array. Since it is also generally
faster than list() = each(), it™s preferable.

continue and break
Within loops you may need to either break out of the loop entirely or skip to the
next item to be addressed in the loop. For these situations, you can use continue
and break, respectively. Both continue and break can accept a numeric argument.
The argument specifies how many levels of loop to break out of. This capability is
rarely used.

Consider a situation in which you™re reading from the file system and would like
your script to address each file in a specific directory, but have no need to address
any subdirectories. When PHP reads names from the directory, you don™t know if
the item is a file or directory, so you need to run a test using the is_dir() func-
tion. You want to skip over listings that are directories. The script looks something
like this:

echo “Files are:<br>\n”;
while ($file = readdir($directory))
if (is_dir($file)){continue;}

echo “$file <br>\n”;
//process files here;

Note that continue isn™t necessary here. You can also code this script as in the
following example, and some feel this a better way of going about it:

echo “Files are:<br>\n”;
while ($file = readdir($directory))
if (!is_dir($file)){
132 Part II: Working with PHP

echo “$file <br>\n”;

break will release the script from a control structure without stopping the execu-
tion of a script. It is almost always best to avoid using break. if statements can
usually accomplish the same thing and make for cleaner code.
A situation in which you might want to use break would be in response to an
error inside your loop. In the following example, we loop through the rows returned
by a MySQL query, calling one function to do some initial processing and then call-
ing a second function to do something with the first function™s results. If either of
those two functions fail, we want to stop the process right there and not continue
with the rest of the rows.

while ($row = mysql_fetch_assoc($result))
$setup_result = setup($row);
if ($setup_result === FALSE)
print “Error in calling ˜setup()™\n”;
$process_result = process($setup_result);
if ($process_result === FALSE)
print “Error in calling ˜process()™\n”;

In this chapter you saw the building blocks of the PHP language. You saw how to
make use of loops and if blocks. If you read Chapter 4, where variables were dis-
cussed, you now know all the basics you need for programming with PHP.
Coding is all about working with variables, loops, and if blocks. The various
combinations of these will take care of everything you will need to accomplish in
your applications. However, one major portion remains to be learned: functions.
Chapter 6 shows how PHP™s built-in functions operate on your scripts.
Chapter 6

PHP™s Built-in Functions

— Using PHP™s built-in functions

— Function syntax

— Working with functions

PHP HAS AN AMAZING NUMBER of built-in functions and extensions (An ˜extension™
is a related collection of functions that are not part of the core PHP code). Many are
available to you only if PHP is compiled with certain options. If, for example, you
need to do some Extensible Markup Language (XML) parsing, PHP has two exten-
sions that can help you. (One uses an event-based approach, the other a document
approach.) If you need Lightweight Directory Access Protocol (LDAP), Internet Mail
Access Protocol (IMAP), or Portable Document Format (PDF) functions, an exten-
sion is there for you. Additionally, PHP has an application program interface (API)
for just about every relational database on the planet. But there™s no need to cover
most of these functions in this book.
Another thing to keep in mind is that the function set is changing almost daily.
PHP is internally structured in a way that makes it extremely easy for programmers
to add additional functions. In fact, if you know your way around C, you can prob-
ably add a new function to PHP in a few hours. So you can expect regular additions
to the core function set.
Your best friend, as always, is the online PHP manual: http://www.php.net/
manual. It™s the only source of which you can be sure that the list of functions will
be more or less up to date. If you want to go directly to the explanation of a func-
tion, all you need to do is point your browser to http://www.php.net/
We want to point out one more thing before we get started here. The final two
portions of this book contain a number of applications. In the course of creating
these applications, we made use of a little over 150 of PHP™s built-in functions. So
while thousands of built-in functions exist, you will probably make regular use of
only a relatively small number.

134 Part II: Working with PHP

A pretty neat resource is the function table at http://www.

Function Basics
Functions all take the same basic form:

return_type function_name (argument1, argument2, argument3)

First, return_type is the type of output that the function returns when called:
integer, Boolean, array, string, and so forth. These are called return values. Next is
the function™s name; note that the name of the function is not case-sensitive.
Finally, following the function name is a set of parentheses. Inside the parenthe-
ses are any arguments required by the function, separated by commas. While hav-
ing any arguments at all is optional, the parentheses themselves are not. We will
discuss arguments first, followed by return values, because that™s the order in which
the function deals with them.

An argument is simply a value (or a reference to a value) that the function is
expecting. A function might expect zero, one, two, three, or more arguments, and
any of the arguments can be of any variable type ” it may be a string, an integer,
an array, or something else. To give you a better idea of what arguments are, here™s
an example: a function that does string handling.
The str_replace() function is extremely helpful. Suppose you have the follow-
ing string:

$str = “My name is Jay.”;

Say that in the $str variable you need to search for Jay and replace it with
John. The function that does the replacement takes three arguments: the string to
be searched through, the string to be searched for, and the replacement string. It so
happens that in PHP, the arguments come in this order:

str_replace(string to search for, replacement string, string to be
searched through);

Or, to put it in practice:

$str = “My name is Jay.”;
$new_str = str_replace(“Jay”, “John”, $str);
Chapter 6: PHP™s Built-in Functions 135

Keep in mind that certain functions will have optional arguments and that a few
will take no arguments at all. Take the substr() function, for example. This func-
tion takes a large string and extracts a smaller string from it by using index num-
bers that are provided as arguments. The letters in the original (larger) string are
numbered (starting with 0 at the leftmost end), and the arguments refer to these
numbers. To get everything from the second character in a string on, you would use
the following code:

$str = substr ($str_var,1);

However, the substr() function also has an optional third argument, which you
can use to limit the size of the string that it returns. A positive value counts forward
from the position given in the second argument. A negative value counts back-
wards from the end of the string. So to get everything from the second character to
the next-to-last character in a string, you would use the following code:

$new_str = substr ($str_var,1,-1);

We™ll point out optional arguments as we move through the functions. The
details of working with substr() will be covered later in the chapter.
On a few occasions a function will take no arguments at all. A good example is
time(), which returns the current Unix timestamp. When this is the case, in the
description of the function in the documentation, the keyword void will be used to
explicitly tell you that the function takes no arguments:

int time ( void)

Return values
When using a function, you should always be aware of what the function will
return ” specifically, what variable type. In the previous case, str_replace()
returns a string. What you do with this string is your business. You could assign it
to a variable or print it out, or do whatever else seems appropriate. The following
code echoes its output string:

//assign to variable
$new_str = str_replace(“Jay”, “John”, $str);
//print directly
echo str_replace(“Jay”, “John”, $str);

Note that functions can return arrays, integers, doubles (floating-point num-
bers), objects, floats (long floating-point values), or (sometimes) Boolean values. In
Chapter 5 you saw a good example of a function that returns a Boolean value (that
is, TRUE or FALSE). If you want to determine whether a variable is an array you can
use the is_array() function, as in the following.
136 Part II: Working with PHP


. 26
( 132 .)