Appendix A. A whistle-Stop Tour of PHP Syntax – Zend Framework in Action

Appendix A. A whistle-Stop Tour of PHP Syntax


This appendix covers

  • Fundamental PHP syntax
  • Variables and types
  • How loops and conditionals work in PHP
  • The basics of PHP functions


Zend Framework is a powerful framework and it’s piquing the interest of a wide range of users, from PHP developers who want to take their sites and skills to the next level to developers from other languages and environments looking to build sites in PHP. The content of this book isn’t for beginners, and the code assumes a reasonable level of PHP knowledge. This appendix and the next are intended to provide a whistle-stop tour of the core PHP concepts you’ll need to know. Obviously, these appendices aren’t a substitute for a complete book on the subject.

This appendix covers the key points of the PHP language that you’ll need to know to make sense of this book. It’s intended for people who understand programming but aren’t well versed in the nuances of PHP. If you don’t know the fundamentals of programming, we suggest that you consider PHP and MySQL Web Development by Welling and Thompson—it’s an excellent introduction to PHP development and programming for the Web. Another good book that goes beyond the basics is PHP in Action by Reiersøl, Baker, and Shiflett.

We’ll start our tour with a look at the fundamentals of PHP then move on to consider the most common PHP operations using arrays and string manipulation. Finally, we’ll look at how PHP interacts with a web server. Appendix B will pick up from there and discuss object orientation in PHP, along with the more advanced concepts of the Standard PHP Library and software design patterns.

A.1. PHP Fundamentals

PHP is very much a pragmatic language designed to enable you to create web pages easily and quickly. It inherits much of its syntax from C and Perl, with a smattering of other inspirations, such as Java for its object-oriented additions.

Listing A.1 shows a basic program with most of the fundamental constructs.

Listing A.1. A Simple PHP Script, Listing1.php

To run this code, we simply type php listing1.php on the command line. Alternatively, if the file is stored within the web root directory of a web server, we can navigate to it in a web browser. This code is very simple and produces the following output:

  Hello Rob
  G'Day Nick

As you can see in listing A.1, each line in PHP ends with a semicolon, and all structures are bounded by braces. Also, because it’s a web language designed to be interspersed with HTML, you must start a PHP code block with the <?php statement and end it with ?>. If there is no other code in the file, you can omit the final closing ?>.

A function in PHP uses the function keyword followed by the function name and then parentheses enclosing any function arguments . The content of the function is enclosed in braces and is executed as shown . All conditional statements have the same basic structure as the if() statement . There are two key types of strings in PHP: single-quoted strings and double-quoted strings. When using single quotes, the text is output exactly as typed, but with double quotes, any variables within the string are changed to the value of the variable (also called variable interpolation).

PHP programs are usually separated into many files. The include and require keywords are used to load and execute a file from within another one. For example, to load the b.php file, the following code would be used:

  include 'b.php';

As the number of files in a project grows, it can be quite hard to keep track of all the times a given file is included. To prevent loading the same file twice, the keywords include_once and require_once can be used. These work exactly like include and require, except that they don’t load the file a second time if it has already been loaded.

Let’s look in more detail at some of the basic constructs within PHP, starting with variables and types.

A.2. Variables and Types

Variables in PHP start with a $ symbol and are loosely typed, as opposed to C or Java variables, which are strongly typed. This means that you can store any type of data into a variable without worry. Also, the language will automatically convert between types as required by the context of use. For example, if you have a string in one variable and a number in another, PHP will convert the string to a number in order to add them together.

A full explanation of PHP’s type-juggling rules can be found at Table A.1 lists the most important types found in PHP.

Table A.1. PHP data types

Data type


boolean A scalar type that can be either true or false (case insensitive).
int Any number without a decimal point, such as −2 or 0x34 (hexadecimal).
float Any arbitrary precision number including a decimal point, such as 3.142 or 6.626e–34.
string Any series of characters, each one byte long, such as “hello world”.
array A map of values to keys. The key can be either numeric, starting at 0, or an arbitrary string, such as $a=array('a', 'b', 'c'); or $a[0]='a';
object A grouping of variables and functions, such as class user
protected $_name;
function getName() {
return $this->_name;
resource A reference to an external resource, such as a file pointer or a database handle. For example, a resource is created when opening a file using $fp=fopen('filename');
null A variable with no value. The keyword null is case insensitive.

In PHP, you don’t need to declare a variable before first use, so the act of assigning a value to a variable using = will create the variable if it doesn’t exist. If it does exist, the value of that variable is overwritten.

It’s also possible in PHP to create a variable variable. This is a variable whose name is set dynamically using another variable. Here’s an example:

  $a = 'name';
  $$a = 'Rob';

This means that there is now a variable called name whose value is Rob. Hence, we can display this using

  echo $name;

This will produce the output Rob.

The string type in PHP is fully featured and contains a number of gotchas, so let’s look at those next.

A.2.1. Strings

Strings in PHP can be declared in four different ways:

  • Single quoted
  • Double quoted
  • Heredoc syntax
  • Nowdoc syntax (PHP5.3 or higher)

We’ll look at each one in turn.

Single-Quoted Strings

The simplest string is the string literal, which is defined using the single quote character, like this:

  $name = 'Rob';

There are two special characters within a string literal: the single quote and the backslash. To use either within a string, escape it with a backslash, like this:

  $name = 'Rob\'s to do list';

If you want to store a backslash in the string literal, you can escape it with a backslash, which is known as a double backslash.

Double-Quoted Strings

Double-quoted strings allow for special escape sequences to be used for special characters. This includes \n for line feed and \t for tab. For example, to display a multiline string, you’d write this:

  echo "This is line one\nThis is line two\n"';

You can also create a string over multiple lines in the file and PHP will create it as multiline too.

The full list of escape characters can be found in the PHP online manual at Again, a double backslash is used if you want a literal backslash in the string.

More importantly, as we noted when looking at listing A.1, variables within double-quoted strings are expanded to their values. There are two types of syntax for variable parsing within strings: simple and complex (which adds braces to the simple syntax).

Simple variable parsing is used more often. When a dollar sign is found in the string, PHP takes the next sequence of characters up to a punctuation mark as the variable name to be expanded. Listing A.2 shows examples of simple variable expansion within double quoted strings.

Listing A.2. Simple variable expansion within strings

Note that the use of an array within a string is a special case, and usually you need to delimit a string that is within an array’s square brackets with quotation marks.

The complex syntax merely adds braces around the variable name, as shown in listing A.3.

Listing A.3. Complex variable expansion within strings

As you can see, when using the complex variable expansion syntax, you can use multidimensional arrays, and even object methods will work.

Heredoc Strings

Heredoc strings allow for both single and double quotes within a string block without escaping. This format uses the <<< operator followed by an identifier to start the string. The string is terminated when the identifier is next encountered at the start of its own line. Here’s an example:

  $name = 'Rob';

  echo <<<EOT
  There's "$name".


That produces this output:

  There's "Rob".

As you can see, any variables within a heredoc string are expanded using the same rules as for double-quoted strings.

Nowdoc Strings

Nowdoc strings are simply heredoc strings without any parsing. They work exactly like single-quoted strings but use the heredoc syntax. They’re created in the same way as heredoc strings except that the identifier is enclosed in single quotes. Here’s an example:

  $name = 'Rob';
  echo <<<'EOT'
  There's "$name".

That code produces this output:

  There's "$name".

This means that nowdoc strings are ideal for large bodies of text, such as PHP code, without worrying about escaping.

That’s all the ways a string can be created, so let’s look at the array syntax next.

A.2.2. Arrays

Arrays are used for lots of different data structures within PHP, because there are lots of functions available that manipulate arrays. Arrays can be treated as arrays, lists, hash tables, dictionaries, collections, stacks, and queues.

In comparison to strings, arrays are relatively simple, because they can only be specified in two ways. The first is by using the array() keyword, like this:

  $users = array('Rob', 'Nick', 'Steven');

The second is directly by assignment, like this:

  $users[] = 'Rob';
  $users[] = 'Nick';
  $users[] = 'Steven';

Both examples result in an array with three elements that have indexes 0, 1, and 2.

Arrays can also be associative, using strings for the key, like this:

  $['author'] = 'Rob';
  $['reader'] = 'Fred';

Finally, arrays can be multidimensional:

  $users = array(

      array('name'=>'Rob', 'country'=>'UK'),
      array('name'=>'Nick', 'country'=>'Australia'),
      array('name'=>'Steven', 'country'=>'Australia')

The preceding example will generate this output:

       [0] => Array
              [name] => Rob
              [country] => UK

       [1] => Array
              [name] => Nick
               [country] => Australia

       [2] => Array
              [name] => Steven
               [country] => Australia

Note that the key for an array can be either an integer or a string. If the key isn’t specified, 1 is added to the maximum integer already in use within the array. If there isn’t an integer in the array, 0 is used.

We’ve now looked at all the data types in PHP, so we’ll move on to look at looping and conditional structures.

A.3. Conditionals and Loops

As a PHP script is simply a series of statements, the loops and control structures are the part of the script that does the work to achieve a specific goal. A loop allows for executing the same code multiple times, usually with changing variables so that similar, but different, results occur. Conditionals allow for branching the code so that only certain parts of the code execute if a condition is met. We’ll start with conditionals.

A.3.1. Conditionals

There are two main conditional constructs: if and switch. The syntax of the if statement is shown in listing A.4.

Listing A.4. The if() syntax

Listing A.4 shows that an if construct contains a conditional statement between parentheses, and the code to be executed if the conditional evaluates to true is between braces. The elseif statement, which works exactly the same as using else if, provides for multiple conditionals to be tested for. Finally, an else statement allows for a block of code to be executed if all the other conditionals fail.

The switch statement is essentially a series of if-else statements, where you compare the same variable with a series of alternative values, as shown in listing A.5.

Listing A.5. The switch() syntax

Note that the switch statement will continue executing from the first matching case statement until the end unless you break out. The default keyword is matched if all the preceding cases fail, and it must come last if you use it.

Both if and switch alter the flow of operation based on conditions. We’ll now look at looping, which allows you to perform the same task multiple times.

A.3.2. Looping

There are four main looping constructs: while, do-while, for, and foreach. They all allow for a statement or block to be executed a number of times. We’ll start with the while loop.

Using while() and do-while()

The while loop is the simplest loop. Here’s an example:

  $i = 0;
  while ($i < 10) {
      echo "$i\n";

This code tells PHP to execute the block repeatedly until $i is 10 or greater. Note that execution doesn’t stop until the end of the block. Also, if the conditional evaluates to false immediately, the block doesn’t execute at all.

If you need the block to execute at least once, use do-while, like this:

  $i = 0;
  do {
      echo "$i\n";
  } while ($i < 10);

In the case of do-while, the conditional is checked at the end of each iteration rather than at the start.

You can finish the execution of a loop early by using the break statement; the continue statement is used to restart the loop before it gets to the end of this iteration. These are shown in listing A.6.

Listing A.6. Using break and continue within loops

The code in listing A.6 executes the loop five times and produces the following output:


The continue statement sends execution back to the while() statement without the echo of $i. The break statement stops the while loop completely when $i is 5.

The while and do-while loops are generally used when you don’t know how many iterations are required. When you know how many times you want the loop to execute, the for loop is used.

Using for()

The for loop constructs are the most complex in PHP, and they work like for loops in C. Listing A.7 shows a for loop in action.

Listing A.7. The for() syntax

A for loop contains three expressions within the parentheses. The first expression ($i = 0 in listing A.7) is run once before the loop starts. The second expression ($i < 10 in listing A.7) is evaluated at the start of each loop, and if it’s true, the block of statements within the brackets is run. If it’s false, the loop ends. After the block of statements has executed, the third expression ($i++ in listing A.7) is executed. All expressions can contain multiple statements separated by commas.

The final looping construct, foreach, is a simplified version of the for loop for iterating over arrays.

Using foreach()

The foreach loop only works with arrays and objects. It iterates over each element in the array and executes a block of statements for each one in turn. This is shown in listing A.8.

Listing A.8. The foreach() syntax

Each time through the foreach loop, the value of the current element is assigned to $value and the key to $key. The code in listing A.8 would produce the following output:

  0: Rob
  1: Nick
  2: Steven

The key is optional, but the value part is not. Note that the value variable ($user in this case) is a copy of the value from the $users array. If you want to modify the original array, you need to reference it using a & symbol, like this:

  foreach ($users as &$user) {
      echo "$key: $user\n";

We’ve now covered the major looping constructs in PHP. To wrap up this section, we’re going to look at an alternative syntax that allows us to forego the braces around the nested blocks of code.

A.3.3. Alternative Syntax for the Nested Block

There is an alternative syntax for both loop and conditional control structures that is widely used in Zend Framework view scripts. This form replaces the opening brace with a colon and the closing brace with a new keyword—endif, endwhile, endfor, endforeach, or endswitch, as appropriate. This is shown in listing A.9.

Listing A.9. Alternative syntax for control structures

The alternative version is most commonly used when PHP is mixed directly with HTML. In this scenario, each PHP statement is surrounded by PHP’s opening and closing statements so that plain HTML can be used between each conditional test. The example in listing A.9 has only one line of text, but in a real application there would usually be many lines. The alternative syntax is used because it’s relatively difficult to match up braces when opening and closing the PHP blocks so often.

We’ve now looked at the key features of PHP’s looping and conditional control structures, so it’s time to move on and look at organizing our executable code using functions.

A.4. Functions

A function is a block of code that is separated from everything else. This allows us to reuse a block of code multiple times without having to copy and paste the same code. The code within a function is also isolated from other PHP code and so is easier to test, and we can be sure that it isn’t dependent on any other code. Listing A.10 shows an example function.

Listing A.10. An example of a function to display a name

A function is declared using the function keyword followed by the name of the function and parentheses. If the function takes any parameters, these are listed between the parentheses. The function in listing A.10 takes one parameter ($name) and displays it after it has converted the first character to uppercase using another function called ucfirst() .



All functions are in the global scope, and you can’t have two functions of the same name. There are many thousands of PHP functions within all the extensions that are available to PHP. As a result, you should consider naming your functions with a prefix, such as your initials, to avoid clashes.


The function in listing A.10 is executed like this:

  $result = hello('rob');

It produces this output:

  Greetings Rob

Obviously, most functions are considerably more complex than this.

Any variables created within the scope of a function aren’t available outside the function definition. The easiest way to have a function provide information is to use the return keyword . In the case of the hello() function in listing A.10, the returned value is true, which is assigned to the $result variable.

A.5. Summary

This concludes our look at the fundamental syntax of PHP. There is obviously much more to the language than we’ve covered here, and the online documentation should be consulted for the fine details on syntax and usage. PHP also comes with many extensions that provide additional built-in functions to the language. The range of functions give PHP its power as a web language. The most common extensions cover databases, XML parsing, file system interfaces, encryption, character encoding, image processing, email, and more.

As this is a whistle-stop tour, there is more we haven’t covered than we have! We’ve covered the key areas of variables, loops, conditionals, and functions at a high level, which should be enough (along with appendix B) to understand the code in this book. The PHP manual’s Language Reference has further details on the nuances of what has been covered ( The rest of the PHP manual has full coverage of all the thousands of functions provided by extensions. Each function has its own page in the manual, which provides details on usage, return types, and examples.

PHP5 vastly improved the object-oriented features of the language. As Zend Framework is an object-oriented framework, all of the functionality it provides is in the form of objects. Appendix B looks at the key features of the PHP object-oriented system that you need to know in order to understand Zend Framework.