Chapter 5. Learning PHP Control Structures and Functions

It's difficult to write interesting programs if you can't make the course of program execution depend on anything. In a weak sense, the behavior of code that prints variables depends on the variable values, but that is as exciting as filling out a template. As programmers, we want programs that react to something (the world, the time of day, user input, or the contents of a database) by doing something different.

This kind of program reaction requires a control structure, which indicates how different situations should lead to the execution of different code. In Chapter 4, we informally used the if control structure without really explaining it; in this chapter, we lay out every kind of control structure offered by PHP and study their workings in detail.


Experienced C programmers: Of all the features in PHP, control is probably the most reliably C-like — all the structures you are used to are here, and they work the same way.

The two broad types of control structures we will talk about are branches and loops. A branch is a fork in the road for a program's execution — depending on some test or other, the program goes either left or right, possibly following a different path for the rest of the program's execution. A loop is a special kind ...

Get PHP6 and MySQL® 6 Bible now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.