Chapter 2. Building PHP Scripts

In This Chapter

  • Setting up conditions in your code

  • Using conditional statements

  • Building and using loops for repeated statements

  • Using functions

  • Keeping your code clean and organized

PHP scripts are a series of instructions in a file named with an extension that tells the Web server to look for PHP sections in the file. (The extension is usually .php or .phtml, but it can be anything that the Web server is configured to expect.) PHP begins at the top of the file and executes each instruction, in order, as it comes to it.

Instructions, called statements, can be simple or complex. Chapter 1 in this minibook discusses simple statements, such as the echo statement. For example, the Hello World script in Chapter 1 in this minibook is a simple script containing only simple statements. However, the scripts that make up a Web database application aren't that simple. They are dynamic and interact with both the user and the database. Consequently, the scripts require more complex statements.

Complex statements execute one or more blocks of statements. A block of statements consists of a group of simple statements enclosed by curly braces, { and }. PHP reads the entire complex statement, not stopping at the first semicolon that it encounters. PHP knows to expect one or more blocks and looks for the ending curly brace of the last block in complex statements.

The following complex statements are described in this chapter:

  • Conditional statements: Statements that execute only when certain conditions are met. The PHP conditional statements are if and switch statements.

  • Loops: Statements that repeatedly execute a block of statements. Three types of loops are for, while, and do..while loops.

  • Functions: Statements that can be reused many times. Many tasks are performed in more than one part of the application. PHP allows you to reuse statement blocks by creating a function.

Conditional statements and loops execute a block of statements based on a condition. That is, if a condition is true, the block of statements executes. Thus, to use conditional statements and loops, you need to set up conditions.

In this chapter, you find out how to use complex statements and how to organize them into a PHP script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.170.206