H-129, Palri, Hodal, Palwal, HR
+91 9992755268

PHP Break and Continue Statement

Just as you saw how to break out of a switch statement, you can also break out of a for loop using the same break command. This step can be necessary when, for example, one of your statements returns an error and the loop cannot continue executing safely. One case in which this might occur is when writing a file returns an error, possibly because the disk is full (see Example 4-35).

Example 4-35. Writing a file using a for loop with error trapping
<?php
$fp = fopen("text.txt", 'wb');
for ($j = 0 ; $j < 100 ; ++$j)
{
$written = fwrite($fp, "data");
if ($written == FALSE) break;
}
fclose($fp);
?>

This is the most complicated piece of code that you have seen so far, but you’re ready for it. We’ll look into the file handling commands in a later chapter, but for now all you need to know is that the first line opens the file text.txt for writing in binary mode, and then returns a pointer to the file in the variable $fp, which is used later to refer to the open file. The loop then iterates 100 times (from 0 to 99) writing the string data to the file. After each writes, the variable $written is assigned a value by the fwrite function representing the number of characters correctly written. But if there is an error, the fwrite function assigns the value FALSE. The behaviour of fwrite makes it easy for the code to check the variable $written to see whether it is set to FALSE and if so, to break out of the loop to the following statement closing the file.
If you are looking to improve the code, the line:

if ($written == FALSE) break;

can be simplified using the NOT operator, like this:

if (!$written) break;

In fact, the pair of inner loop statements can be shortened to the following single
statement:

if (!fwrite($fp, "data")) break;

The break command is even more powerful than you might think because if you have code nested more than one layer deep that you need to break out of, you can follow the break command with a number to indicate how many levels to break out of, like this:

break 2;

The continue Statement

The continue statement is a little like a break statement, except that it instructs PHP
to stop processing the current loop and to move right to its next iteration. So, instead
of breaking out of the whole loop, PHP exits only the current iteration.
This approach can be useful in cases where you know there is no point continuing
execution within the current loop and you want to save processor cycles or prevent an
error from occurring by moving right along to the next iteration of the loop. In
Example 4-36, a continue statement is used to prevent a division-by-zero error from
being issued when the variable $j has a value of 0.

Example 4-36. Trapping division-by-zero errors using continue
<?php
$j = 10;
while ($j > −10)
{
$j--;
if ($j == 0) continue;
echo (10 / $j) . "<br>";
}
?>

For all values of $j between 10 and −10, with the exception of 0, the result of calculating 10 divided by $j is displayed. But for the particular case of $j being 0, the continue statement is issued and execution skips immediately to the next iteration of the loop. Implicit and Explicit Casting PHP is a loosely typed language that allows you to declare a variable and its type simply by using it. It also automatically converts values from one type to another whenever required. This is called implicit casting. However, there may be times when PHP’s implicit casting is not what you want. In Example 4-37, note that the inputs to the division are integers. By default, PHP converts the output to floating point so it can give the most precise value—4.66 recurring.

Example 4-37. This expression returns a floating-point number
<?php
$a = 56;
$b = 12;
$c = $a / $b;
echo $c;
?>

But what if we had wanted $c to be an integer instead? There are various ways in which we could achieve this, one of which is to force the result of $a/$b to be cast to an integer value using the integer cast type (int), like this:

$c = (int) ($a / $b);

This is called explicit casting. Note that in order to ensure that the value of the entire an expression is cast to an integer, we place the expression within parentheses. Otherwise, only the variable $a would have been cast to an integer—a pointless exercise, as the division by $b would still have returned a floating-point number.

You can explicitly cast to the types shown in Table 4-6, but you can
usually, avoid having to use a cast by calling one of PHP’s built-in
functions. For example, to obtain an integer value, you could use the
intval function. As with some other sections in this book, this one
is mainly here to help you understand third-party code that you may
encounter

 

Cast typeDescription
(int) (integer)Cast to an integer by dropping the decimal portion
(bool) (boolean)Cast to a Boolean
(float) (double) (real)Cast to a floating-point number
(string)Cast to a string
(array)Cast to an array
(object)Cast to an object

PHP Dynamic Linking

Because PHP is a programming language, and the output from it can be completely different for each user, it’s possible for an entire website to run from a single PHP web page. Each time the user clicks on something, the details can be sent back to the same web page, which decides what to do next according to the various cookies and/or other session details it may have stored. Although it is possible to build an entire website this way, it’s not recommended, because your source code will grow and grow and start to become unwieldy, as it has to account for every possible action a user could take. Instead, it’s much more sensible to split your website development into different parts. For example, one distinct process is signing up for a website, along with all the checking this entails to validate an email address, determine whether a username is already taken, and so on.
A second module might well be one for logging users in before handing them off to the main part of your website. Then you might have a messaging module with the facility for users to leave comments, a module containing links and useful information, another to allow uploading of images, and more. As long as you have created a way to track your user through your website by means of cookies or session variables (both of which we’ll look at more closely in later chapters), you can split up your website into sensible sections of PHP code, each one selfcontained, and therefore treat yourself to a much easier future developing each new feature and maintaining old ones.

Dynamic Linking in Action

One of the more popular PHP-driven applications on the Web today is the blogging platform WordPress (see Figure 4-5). As a blogger or a blog reader, you might not realize it, but every major section has been given its own main PHP file, and a whole raft of generic, shared functions have been placed in separate files that are included by the main PHP pages as necessary. The whole platform is held together with behind-the-scenes session tracking so that you hardly know when you are transitioning from one subsection to another. So, as a web developer, if you want to tweak WordPress, it’s easy to find the particular file you need, modify it, and test and debug it without messing around with unconnected parts of the program. Next time you use WordPress, keep an eye on your browser’s address bar, particularly if you are managing a blog, and you’ll notice some of the different PHP files that it uses.

wordpress
Figure 4-5. The WordPress blogging platform is written in PHP

 

This chapter has covered quite a lot of ground, and by now you should be able to put
together your own small PHP programs. But before you do, and before proceeding with the following chapter on functions and objects, you may wish to test your new knowledge on the following questions