SPSU WebMark
click for Brown's home page

A Gentle Introduction to PHP

School of Computing and Software Engineering
Southern Polytechnic State University
Copyright © 2002 by Bob Brown

What is PHP?

PHP started out as a (relatively) simple server-side scripting language called Personal Home Page, developed by Rasmus Lerdorf. It has grown to a full-fledged programming language supported by scores of open-source developers. At the same time, the meaning of "PHP" has morphed from Personal Home Page to the somewhat recursive PHP Hypertext Processor. You can find the official PHP Web page at http://www.php.net.

Although PHP runs on many platforms, it is integrated into the Apache Web server, so PHP and Apache make a powerful combination. PHP works with many database management systems. We will be using PostgreSQL in our examples, but PHP also works with the other major open source database, MySQL. You can combine Apache and PHP with an open-source database management system to provide a complete database-driven Web server platform. The software cost of such a system is zero.

Hello, World!

PHP programs look a lot like HTML pages. In fact, they are HTML pages with programming mixed in. Blocks of PHP code are enclosed in XML processing instruction marks. (There are actually several ways to do this, but the XML approach is the one that's future-proof.) Here is the HelloWorld program in PHP:

<title>Hello, World!</title>
<?php echo '<h1>Hello, World!</h1>';
      echo '<p>Hello, world!</p>';

This program would be stored in a file with a .php extension and located on the server in an "ordinary" HTML directory. From this simple example we learn several things, most of which are repeated from above for the sake of getting them into a neat list:

The last two statements may need a little more explanation. The .php file extension alerts the Web server program to hand the file off to the PHP processor. The PHP processor has two modes, copy and interpret. The processor starts off in copy mode; text from the file, presumably HTML, is copied to the network connection and sent to the client browser. When a <?php processing instruction is encountered the processor switches to interpret mode. The PHP statements are interpreted, and their output, if any, is sent to the browser. The processor remains in interpret mode until a ?> is encountered, which switches it back to copy mode.

You won't remember this when you need it, but I'm going to tell you anyway so I can say, "I told you so!" later. PHP has functions that can manipulate the HTTP headers. However, as soon as anything is sent to the Web server, the headers are generated and sent. After that, the header functions are invalid. Even a blank line before the first <?php will cause the headers to be generated. (Because the PHP processor starts off in copy mode, that's why!)

PHP Variables

PHP variable names start with a dollar sign. The first character after the dollar sign must be a letter or underscore, which may be followed by any number of letters, digits or underscores. PHP variable names are case sensitive.

PHP is dynamically typed; a variable is bound to a datatype when it is assigned, and a later assignment can change the datatype. PHP has four scalar, two special and two compound datatypes:

Boolean variables have the values TRUE and FALSE. The exact format of the integer datatype is implementation-dependent, but integers are generally 32-bit numbers. Doubles are floating-point numbers; their representation may include a decimal point and optionally an exponent. The exponent is indicated by e or E and a signed integer. Strings are sequences of ASCII-8 characters of (practically) unlimited length. A variable that has never been assigned has the special type and value NULL. We leave resource and array for later. The object datatype is beyond the scope of this tutorial.

Strings, Escapes, Interpolation and Output

PHP has two ways of representing string literals. A string literal enclosed in quotation marks (double quotes) receives special processing by PHP that will be discussed below. A string literal enclosed in apostrophes (single quotes) is taken by PHP exactly as it is written with the exception that you can include an apostrophe in such a string by escaping it with a backslash, like this:

$answer = 'You\'re right!';

When a string is enclosed in double quotes, PHP processes escaped characters, such as \n for new line. Even more useful, it recognizes variables, formats them for readable output, and interpolates them into the string. This makes it very easy to generate output that's a combination of literals and variables:

echo "The answer to everything is $answer.";

prints (sends to the browser):

The answer to everything is 42.

You can include a double-quote in a double-quoted string by escaping it with a backslash. The dollar sign can be escaped with a backslash to print a literal dollar sign rather than attempting variable interpolation.

echo "The answer to everything is \$answer.";

prints (sends to the browser):

The answer to everything is $answer.

Both kinds of strings may contain an embedded new line created by pressing the enter key, like this:

$myString = 'Here is a string with
             an embedded new line.';

This isn't as useful as it might appear. If you output the string, the HTML parser in the browser will suppress the new line unless you are in the context of preformatted text, and it's hard to see what's going on when you read the program.

(There is a lot more to know about PHP strings. You can find a the official PHP documentation at http://www.php.net/manual/en/printwn/language.types.string.php#language.types.string.syntax.single. )

You generate output in PHP using the echo, print, or printf functions. The echo function is the most friendly of these. When used without parentheses, echo takes any number of parameters and copies them to the output stream. Variables given as parameters or enclosed within a double-quoted string are converted to a default output format that is usually what you will want. (If it isn't, you need printf.) Remember that the output is destined for a browser, so if you want formatting, you must emit HTML tags:

echo "The answer is<br /> $answer<br />";

will produce two lines on the browser screen, one with "The answer is" and one with the contents of the variable $answer, then will continue output on a third line because of the trailing <br />.

If you use echo( ) like a function, with parentheses, e.g. echo($answer); you can use only one parameter. Best to leave the parentheses off and treat echo like a keyword rather than a function.

The print( ) functionworks exactly like the echo( ) function, i.e. it takes exactly one operand and sends the operand to the client browser.

The printf( ) function works like its C counterpart, and is used when you need absolute control over the formatting of the output. For example, you might use printf to format a variable of type double as dollars and cents.

Operators and Functions

PHP has the usual arithmetic operators, +, -, * and /. The division operator always returns a double (floating point) type, even if the result is an integer. You can use the intval() function to convert this back to an integer. There is also a modulus operator, %, that returns the remainder after division.

There are increment and decrement operators, ++ and --. These can be used for both post-increment and pre-increment, as in C.

The assignment operator is =. It can be combined with the binary (two-operand) arithmetic operators and string operators. So, the following are equivalent:


PHP implements comparison operators = = for equality, < and > for less than and greater than, <= and >= for less than or equal and greater than or equal. Inequality may be represented by < > or !=.

The period (.) is the string concatenation operator.

There is much more to learn about PHP operators. You can find what you need to know at http://www.php.net/manual/en/language.operators.php.

PHP has more functions than you will ever use in a lifetime. If it can be done, there's a PHP function to do it. You will want to browse the list of available functions at http://www.php.net/manual/en/funcref.php paying particular attention to the following:

An hour or so browsing in the function list will amaze you at the breadth of things you can do with PHP.

Language Structure and Control Statements

PHP statements may be grouped into blocks by enclosing them in curly braces, { }.

The if statement implements the selection construct. There is an optional else part.

if ($a > $b)
   echo "A is greater than B";
   echo "A isn't greater than B (might be equal).";

Both if and else can take a block of statements enclosed in curly braces.

A case-like selection construct can be implemented with if and elseif. An alternative is the switch statement.

Counter-controlled iteration is implemented with for loops:

for ($i = 1; $i <= 10; $i++) {
    echo $i;

A more general iteration control structure is while. We use a counter in the example below, but any expression can be used to control a while loop.

$i = 1;
while ($i <= 10) {
      echo $i;

The while loop is a pretest loop; the conditional expression is checked before the body of the loop is executed. PHP implements the posttest loop with do-while.

$i = 0;
do {
   echo $i;
} while ($i>0);

The value of $i (zero) will be printed exactly one time because the continuation condition ($i>0) is false at the beginning. The body of a posttest loop is always executed at least once.

PHP and JavaScript

During this course, we've discussed the differences and similarities between server-side and client-side programming. By now you've concluded that there's a place for both. Since PHP is entirely server-side, and since the client HTML comes from the PHP program, you might be wondering whether you can use client-side programming, such as JavaScript with PHP. The answer is yes.

Earlier we said that when PHP is in copy mode, the text being sent to the client browser is "presumably" HTML. Clearly, it doesn't have to be. Anything not enclosed between PHP's XML processing instruction marks will be copied to the client. This means you can embed JavaScript in a PHP program document and it'll get copied to the client. You can even emit JavaScript from PHP echo statements.

A Gentle Introduction?

We hope you've enjoyed this introduction to PHP and found it to be sufficiently gentle. Although we haven't yet taken full advantage of the fact that PHP is a server-side programming language, you have enough information to write non-trivial programs, and because the computing is done on the server, they'll work with almost any browser.

Next: PHP Arrays and Forms Handling

Last updated: 2014-10-02 7:17