Introduction to the PHP Language

This is a short introduction to programming with php which is part of my PHP crash course

A web page is a long string of characters. If you are in a web browser, you can view the source of the page. You will see special tags enclosed in angle brackets and regular human readable words. An HTML tag looks something like this: <tag>. We hurried through a discussion of HTML in the first day of the class.

PHP is a program designed to create HTML pages. In other words, it is designed specifically to piece together a long strings of text. The magic word that creates the HTML is called echo. You can think of the echo statement as something that echoes strings of text to the web browser.

echo "<b>Hello World</b>";

This will produce the following HTML text:

<b>Hello World</b>

Your browser will display the HTML string as: Hello World.

Basic Syntax


To excel at PHP you need to know the basic syntax of the language. Since our ultimate goal is to produce strings, we might as well start with a string. In PHP you mark the beginning and end of the string with a quotation mark. The code

"This is a string" 

produces the string: 

This is a string

You can see a slight problem here. Since a string begins and ends with a quotation mark, how can you include a quotation mark in the string? PHP has a special thing called an escape code. To print a quotation mark, precede it with a backslash as follows: \"

Okay, now, how do you produce a backslash? (These computer geeks seem to cause one problem after another.) To produce a backslash, you have to print two backslashes. Here is a list of all the escape codes:


Code Result
\" quotation
\' apostrophe (single quote)
\\ Backslash
\n New Line
\$ Dollar Sign
\t Tab

The other common literal in PHP is the number. You don't put numbers in quotes. If you see the code 123, then you have a number that is between 122 and 124. If you see "123" you have a three character string with the characters "1", "2", and "3". You can add 1+2 to get 3. Trying to add "1" + "2" doesn't make quite as much sense. PHP will convert the characters "1" and "2" into numbers 1 and 2, then add them.

When you start dealing with numbers, you need to pay close attention to the type of the number type. For the most part you will be dealing with integers. These are straight forward numbers without anything to the right of the decimal point. For example, the numbers 1, 123, -14 are integers. For more precise numbers, you will need to use floating point numbers. Since we are mostly dealing with strings. I will ignore the complexities of floating point arithmetic, and stick with the easy stuff.


Literals are static. They cannot change in a program. The next tool in our tool chest is a thing called a variable. Think of a variable as a bucket. It is something that can hold a piece of data. In PHP, all variables begin with a dollar sign ($). In the follow code, I assign the literal "Hello World" to the variable $myVariable, and echo the variable to the screen:

$variable="<b>Hello World</b>";
echo $variable;

Since you cannot add strings and numbers, it is important to remember the type of literal you stuffed into your variable...otherwise you might get errors. Getting things right is a simple matter of practice.

Some times you want to create a pile of similar variables. Rather than having to come up with a new name for each variable, you can create an array of variables. You can then reference each of the items in the array with an index number. To create an array, you can use array() function as follows:


This code creates a three element array, and assigns the values 1,2,3 to the first three elements of the array. It is somewhat confusing, but arrays always start with the number 0, instead of the number 1. In geek speak: they are using an "offset" instead of a "counter." It takes a little getting used to.

There is a lot of cool stuff you can do with arrays, but we want to get programming, and will get back to arrays, when we use arrays. You can really think of each element in an array as a separate variable.


So you now have a pile of strings and literals. You can combine and manipulate variables with things called operators. Here are some common operators:

Operator Name
= Assignment
. Concatenation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (This the remainder. 10 % 7 = 3)
++ Increment
+= Increment Assignment
*= Multiply Assignment
-= Decrement Assignment

The Assignment Operator

PHP uses the equal sign "=" for the assignment operator. The assignment operator is not the same thing as the equal statement used in high school mathematics. The assignment operator means to take the value from right side of the operator and put it in the variable on the left side of the operator. The following code will put the literal value 123 into the variable $a.

$a = 123;

The left side of the operator can contain one and only one variable. The right side of the operator contains a statement that resolves to a literal value. For example the statement 1+2 resolves to the number 3. The following line of code will resolve the statement (1+2) and put the number three in the variable $a:

$a = 1+2;

NOTE: The literal on the left side of the equation should be the same data type as the statement on the right. (see note 1)

Concatenation Operator

As you recall, our ultimate goal is to piece together a bunch of small strings, and make way one way big lumpin' large string called a web page. Concatenation is the fancy Latin term for pasting strings together. PHP uses the dot operator (.) for concatenation. The following code will paste together the three strings: $a." ".$b.

You might try executing the following code:

$a = "Hello";
$b = "World";
echo $a." ".$b;

This should produce the string "Hello World".

PHP does one extremely sneaky thing. You can skip the concatenation operator and stuff a variable directly in a string as follows: (This is why they begin variables with the $ character).

echo "$a $b"; // is the same as $a." ".$b

Mathematical Operators

PHP has the same mathematical operators as other programming languages. + is plub, - is minus, * is multiplication and / is division. These work pretty much like the math you learned in 3rd grade. Except there isn't a third grade teacher towering over your head holding a ruler.

Assignment Operators

PHP includes a number of assignment operators. An assignment operator is a clever little short cut that helps clean up your code, and can make things run a little faster. To understand the assignment operator, you need to understand the way a computer thinks. 

In the following statement, the computer will add the variables $a and $b, then put the result of the operation back into variable $a.

$a = $a + $b;

The assignment operator is nanoseconds faster. The following line of code will add the variable $b directly to the variable $a. This saves the computer from having to create the interim value.

$a += $b;  // same result as $a=$a + b;

It turns out that you will often want to increase a number by 1. PHP has a super fast operation called an increment. The increment operator is two plus signs: ++. The code $a++ increases the value of $a by 1.

Computer programmers like to split hairs. There is a difference between $a++ and ++$a. In the first operation, the program reports the value of $a, then increments it, in the second operation, the program increments the value then reports the value. This is important if you include several operations on the same line. You might run the following code:  

echo "<br>first value ".$a++; // returns 5
echo "<br>The value now is ".$a;
echo "<br>Second Value: ".++$a; // returns 6
echo "<br>The variable is ".$a;

To keep my code clean, I usually just leave the increment operator on its own line. (see note)~~

Comparison Operators

The final group of operators are called comparison operator, and logical operator. The comparison operators return a boolean value. A boolean value is either true or false. The word boolean comes from a English Logician with name Georg Boole (1815-1864).

You can use logical operators to combine comparison operators. These operators are:

Code Name
== equals
> greater than
< less than
>= greater than or equal to
<= less than or equal to
!= not equal.
Both statement $a && $b are true
Either statement $a || $b is true.
xor Exclusion or. Either one value is true or the other is true,
but not both.
! Not

The equal operator is the most commonly used operator. Notice it is two equal signs, while the assignment operator is one equal sign. This is a common source of accidentally put two equal signs when you meant one or visa versa. Mixing up the equal signs is one of the most common errors.

A comparison operator resolves to either a true or false. You can stuff the result of a comparison operator into a variable, then use that variable later on in the computer. Your code may look like the following.

$hasAccess =  ($securityLevel > 10);
// later on in the code you ask
if ($hasAccess) { echo "The secrets are..."; );

You can combine the comparisons with the logical operators. For example, you might have to check to see if your user is both above 13 and speaks Hindi, as follows:

if ($age > 13 and $language="Hindi") {
  // display page.

You may have noticed that there are two versions of the word or. You can write or as "or" or "||". These operators behave differently. The standard version of the word or will evaluate both sides of the equation. The || version will evaluate the left side of the comparison. If it is true, the program will stop. If it is false, it will evaluate the right side of the comparison. The || variable is a little bit faster, but I like to use the word version. It makes the code clearer, and sometimes you want to evaluate both sides of the comparison. (see note)

Operator Precedence

You can combine operators in a single statement. Operator precedence determines the order that the program executes statements. For the most part operator precedence is intuitive. You can remember from high school that 1 + 3*4  = 13. You do the multiplication first, then the addition. You can over ride operator precedence with the parentheses. In our math example (1+3)*4=16.  The following table shows operator precedence:

 Operator Operation Name 
 ()  parenthese (highest, will override other precedences
 []  Array assignment
 !  Not
++  -- increment/decrement
* / % multiplication, division & modulus
+ - . Addition, Subtraction & concatenation
 > >= < <=
== !=
Comparison operators
&& || Logical and, logical or
= += -= 
*= .=
Assignment operators. 
and xor or The add logical operator.
, comma.


Parentheses () have the highest precedence. You can use parentheses to combine things. You use commas to separate things. The difference between || and the word or is that || has a higher precedence than the assignment operator. The regular or has a lower precedence. (see note)

Programming Structure

A program is a list of instructions that you give to a computer. You can imagine the computer starting at the top of the page, and reading your instructions line by line to the bottom of the page...doing exactly what it is told. (It is really horrible, computer programs do what you tell them, not what you meant.)

Of course, if the computer program reads from the top of the page to the bottom, it won't do anything very interesting. You make program interesting through your program's structure.

Basically, programming structure will do one of two things. It will either skip code, or repeat code.

if all else fails

The if statement skips code. The syntax for this statement is 

if (comparison) { 
  // do something 
} elseif (anotherComparison) {
  // do something else
} else {
  // do something altogether different;

As you can see this is a relatively simple structure. This structure will do one of the three options. It  will either "do something," "do something else" or "do something altogether different."

Important things to note. You need to replace comparison with a statement that returns true or false. The little curly brackets indicate the beginning and end of a structure. When you debugging code, you will learn to follow chunks of code from curly bracket to curly bracket.

Personally, I am a very big believer in indenting code. As you may have noticed, I indented the lines between the curly brackets. Since you can nest programming structures inside other programming structures, you will find that proper indentation can simplify your code.

You can have any number of elseif statements inside an if structure. Here is code that a bank might use to treat customers differently depending on the value in the variable $netWorth.

if ($netWorth < -100000) {
  echo "Here is a the number of a good attorney";
} elseif ( $netWorth < -10000 ) {
  echo "Please see our debt consolidation department.";
} elseif ($netWorth < 0) {
  echo "You will find the soup kitchen on the corner of 3th south and main.";
} elseif ( $netWorth < -100) {
} elseif ( $netWorth < 1000) {
  echo "We don't want your kind around here.";
} elseif ( $netWorth < 20000) {
  echo "You can use the automated teller on the street.";
} elseif ( $netWorth < 100000) {
  echo "Hey, nice tie.";
} elseif ($netWorth < 750000) {
  echo "Please see our secretary.";
} else {
  // this will only happen with netWorth >= 7500
  echo "Great to see you, come in. We are the best of friends.

The code above will execute only the first true statement. It will ignore everything else.

PHP includes another program for skipping code called the switch statement, which you can look up in the documentation.

While It Lasts

The next group of control statements causes code to be executed multiple times. There are several different ways of writing such code. The most intuitive structure is the while loop. The following while loop should execute 10 times. (You should test this code in a compiler):

while ($i<10) {
  //this is the inner loop.
  $i++;  // increment the variable $i.
  echo "<br>The number is: $i";

The stuff between the curly brackets will execute until the condition in the while loop is satisfied. If I forgot the $i++ statement, the program would never end. I would be in an infinite loop. Always make sure that there is a way to get out of your infinite loop.

A lot of programmers like using a structure called a for loop. It is like a while loop, but the it builds the incrementing of the variable into the structure of the command. The for loop looks like:

for ($i; $i<10; $i++) {
  echo "The value of  i is $i";

The advantage that the for loop has over the while loop is that it is harder to forget putting in the end statement. The disadvantage is that you have to know in advance how many times the loop will execute before running the statement. I tend to use while loops, but I am very careful to make sure I include a condition that will eventually evaluate to false.


The final thing I want to look at is a function. You can write a program from top to bottom using if and while statements. You will be able to get the program to do whatever you want it to do. Unfortunately, your code will become long, complex and difficult to read.

The function structure helps you make sense of complex programs. Basically a function is a named block of code.  The structure of function is as follows:

function myFunction($parameter1,$parameter2) {
  global $globalVariable; // A global variable..not passed as a parameter.
  // do stuff
  return $returnValue;

Using functions makes your code cleaner. It also lets you reuse code since you can call the function more than once.

You feed information into the function with parameters. PHP can only see variables passed as parameters, or that you declare as global with the global statement. (That way you don't have to worry about making sure your local variable names in your functions are unique. In the following code, I will create two functions. The first is called myLink. This function will create an HTML hyperlink. I will call the second function tableRow. This function will create HTML rows that alternate in color.

$rowNumber = 0; // the number of the row.
function myLink($linkName,$linkURL) {
  global $rowNumber; // what would happen if I remove this row.
  if ($rowNumber++%2 = 1) {
  } else {
  return "<a href=\"http://$linkName\" bgcolor=$rowColor>$linkURL</a>";

function tableRow($rowData) {
  echo "<tr><td>$rowData</td></tr>\n";
  // why did I include an \n at the end of the string?

echo "<table align=center>";
tableRow(myLink("Salmon Idaho",""));
tableRow(myLink("Pendleton, Oregon","");
if ($userIsFunkyEnough) {
  tableRow(myLink("Mystic Dance","");

We have now learned enough stuff to become dangerous. It is time to open an editor and start some coding. Here are a couple of assignments to try.

Back to PHP.

Web browsers are actually a little more complex than that. PHP writes to a buffer that gets sent via HTTP to your browser. Still, you can think of PHP as echoing data to your screen. You can think what ever you like. I like to think in whatever way makes my life easy.

1) PHP is loosely typed, and will let you get away with things that would break in a strongly typed language. If you were in java the code "1"+"2" would produce a string "12". Other languages would spit out an error.

The following code should show you the different between ++$a and $a++. The difference only shows up when you combine operators. Personally, I like to put $a++; on its own line, and not have to think too much:
if ($a++ >0) {echo "This will not show since we did the comparison before the increment.";}
if (++$a >0) {echo "This should show since we incremented then compared."; }

One of the most common errors is to confuse a single equal with a double equal. = and ==. = is an assignment and == is a comparison. When you leave off the second =, you get spurious results. Check out the following code:
if ($x=3) {
  // This is a common used an assignment in the condition area.
  echo "The value of x is $x. The if statement assigned the value 2 to x, and reported true.";
} else {
  echo "This code does not execute.";