PHP Primer

What is PHP? That’s like asking, “What is life?” PHP is life. It is the life blood of the web based Universe. Sure you have opposing forces in C#.net and other web technologies, but PHP is what keeps those other languages on their toes.

In short, PHP is a very versatile server side scripting language. It is used to communicate information between the user and the server. A User sends a request to the server, PHP parses it, sends that information to the database or processes it itself and then spits the results back to the user.

Its power is astounding, empowering, intimidating and threatening all in one. It can be used for good, bad and ugly. What comes out of programming in PHP is all up to you, the programmer.

I am going to assume, for the purposes of this book, that you are familiar with basic programming skills and knowledge of the underpinnings of the Internet.

Understanding Web Technologies

What do you need to know to get started? Well, we need to look at some of the technologies that make PHP the powerful language it is.

First, let’s look at LAMP. No, not the light source next to your couch. We are talking about “Linux, Apache, MySQL and PHP” These are the four technologies that power a large number of websites and applications you probably use on a daily basis. You know Twitter? It sues LAMP. Facebook? LAMP. Wikipedia? LAMP. The list goes on.

These four technologies are made so powerful because they all subscribe to a philosophy of Free Open Source Software. This means that anyone with the ability to program can help improve the functionality, stability and form of these tools. This helps not only the technologies but also the people who use them on a regular basis.

In case you are not familiar with what each of these are, here is the run down.

Linux – The operating system of the server. This allows all the software to access the processors, RAM and storage on the server, as well as the other hardware components. It is similar to the operating system you use on your personal computer.

Apache – This software is what turns your computer hardware and operating system into a web server. It handles all the translation of your URL string into an actual request to the server script. Without this, your server is just a computer with an Ethernet cable plugged into it.

MySQL – This is your database. This is where all the information your website needs to run is stored. You will be filling it up with content from your website, user data and just about everything else.

PHP – As I said above, this is what takes the command sent from Apache and processes it.

Not all these technologies are set in stone. There are many configurations of software that you can use. For instance, you could use a Windows operating system, and IIS server, ASP.Net and T-SQL database. However, that doesn’t have a snazzy acronym. So we won’t be using it.

Getting Started

In order to get started with PHP programming we need to do a few things. First we will need to set up a test server and a development environment.

There are plenty of tutorials online for setting up a LAMP server and if you already run Linux it is even simpler. So I really won’t go into it. You will be putting your PHP code onto this server so that it can run.

I will however focus more on a development environment. These are what I use. Your mileage may vary and you don’t have to use what I do.

For all my PHP programming needs, I use the Eclipse IDE. This is a versatile and expandable IDE. You can download a version of Eclipse that is automatically set up for PHP development. This means that it supports PHP scripting language highlighting and templates for frequently used clocks of PHP code.

Another great reason to use Eclipse is that it comes with a plugin to directly interface Subversion, Subclipse. This makes it easier to manage your source code and protect yourself from screwing up royally. Version control is another technology that I will not explain in depth as there are plenty of tutorials and instructions on its use. I will however emphasize the necessity of using version control. This will save your programming life.

What version control does is keep track of changes you make to source code for any language. It allows you to compare different versions, revert to older versions and all around help you get out of the corner your coded yourself into. Use it. Live it. Love it. The Subclipse plugin will help you in this lifestyle.

Now that we have an IDE, a test server and version control, we are ready to get programming.

The World’s First Project

As with any programming language, we need to start with something awesomely simple. A “Hello World!” program. If you installed your LAMP server, it will come with a nice “Hello World!” style script that let’s you know you installed the software properly.

Yet, “Hello World!” is so passe and I won’t be using it. We will use the much superior phrase “All your base are belong to us.”

Here is the code to declare that mighty of phrases. We will put this code into a file named “index.php”

<?php
    echo(“<h1>All your base are belong to us.</h1>”);
?>

What? You thought it would be more complicated than that? That was too easy? How can that create a web page? Well it does. That is the power of PHP.

To help explain a little of what is happening in the above mighty script, I will explain each line.

The first line is the opening of the PHP script. “<?php” This tells the server to treat what follows as script and not HTML.

The second line is an echo statement. You use this function call to print any text you want to the user’s browser. You could also use the function call “print” to do the same thing. There are two differences between print and echo. First, print will return “1” upon success; echo does not do this. The other difference is that echo will take multiple parameters and print each one; print only takes one parameter.

Finally, we close out the script with a revers of the first line without the “php” This tells the script we are done processing.

Now let’s look back at that echo statement. Notice the use of double quotes. PHP allows you to use double and single quotes to define a string. There is a difference in them. Double quotes allow you to embed a variable into the string without concatenating it. Single quotes force your to concatenate.

For example see the following code:

<?php
    $var = 'foo';
    echo(“$var bar”);
    echo('$var bar');
?>

In this, the first echo statement will print out “foo bar” and the second will print out “$var bar”. To make the second work, you will have to write it as follows:

    echo($var.' bar');

In this one, we use the php concatenation operator . That is a period. PHP does not use the + operator for string concatenation.

Another thing to note is that with either method, you can include the other in the string without needing to escape them. So you can do the following:

    echo(' ”Hello” ');
    echo(“ 'Hello' “);

Otherwise you would end up with statements that look like this:

    echo(' \'Hello\' ');
    echo(“ \”Hello\” “);

This is not pretty and you will be bleeding out your eyes if you do it too often. Stick to the other way as it is much cleaner.

Now I went an did it. I introduced a new concept while trying to explain another. Now I have to give a brief explanation of variables.

PHP variables are a bit different that most other languages. In PHP, all variable start with a dollar sign “$” In PHP, variables do not have to be defined as a specific type. Nor do they need to be defined with a “var” statement. All you need to do is name the variable and give it some kind of value.

Be careful with this new found power. It can be easily abused and can give you nightmares when it comes to debugging your script. If you attempt to do math on a variable that has been defined as a string, you could be given an error if you don’t explicitly cast it. I will get to type casting later.

So there we have it. Our first PHP program. Don’t you feel like you could conquer the world now?

Documentation

In the world of programming, there are two types of documentation methods. I will call them “explicit documentation” and “self documentation” Both are awesome and you should use them in conjunction throughout your code. So let’s explain what these two mean and how to use them.

Explicit Documentation

Explicit documentation is when you write out in plain written language what something you are about to do or have done means. This is usually done with PHP comment blocks.

<?php
    /*
    This function returns a string with the passed in parameter as part of it.
    */
    function a($b)
    {
        return "Hello $b";
    }
?>

In this example we have a comment block using the PHP designators “/*” and “*/” This tells the script that what is between these two symbols are to be ignored and not acted upon. There is also a second form of commenting which is defined by the use of “//” This only comments out a single line while the former is used to comment out several lines.

Now this comment documents the purpose of the function. It tells someone who is looking at the code what you are doing.

However, this has some weaknesses, not all together a result of the documentation method itself. This weakness lies with the function name. Which brings us to the second type of documentation, self documentation.

Self Documentation

Now look at that block of code above. What is wrong with it? If you said the name of the function, you are correct. The name of the function “a” doesn’t really tell you anything about what the function does. If you were to have this function called in another PHP script, you might not know exactly what is happening. See the following.

<?php
    echo(a("Bob"));
?>

Someone looking at this block of code would be left wondering what the function “a” is and what it does. This is why we use self documentation.

Self documentation is the use of variable and function names that describe what they are or do. So instead of using the function name of “a” we will change it to “create_greeting” This more clearly describes what the function does.

Additionally, we have the parameter inside the function definition. This parameter does not describe what is to be passed into the function. It would be better to use a variable name such as “$name” rather than “$b”. This would tell the person who will be using the function that you are expecting a name to be passed into the function.

Feel free to create your own guidelines for naming functions and variables. Some people like to use camel casing (createGreeting) or underscores (create_greeting) or whatever. I personally use underscores between words in functions and camel casing for variables. The key is to be consistent with whatever conventions you use. If you are consistent, any programmer, regardless of conventions they have used in the past, will be able to read and understand your code.

Variables

We have used a few variables already, but we have not really discussed them in any great detail. So let’s get started.

PHP is not a strongly typed language, this means that there are very little restraints on the use of variables. This can get you into a world of trouble if you are not careful. Debugging a language like PHP can be a lesson in frustration if you are not consistent in your code and careful in its execution.

So how does one use variables in PHP? Well, first things first, we need to name our variables. To do this we use the dollar sign ($) to identify that what you are about to type is a variable. Without it, PHP attempts to define it as one of the many constants or function names in PHP itself and your own code. If it can’t find something to match it will error out.

<?php
    //invalid variable
    var = '';

    //valid variable
    $var = '';
?>

You can also define PHP variables anywhere in your code. In some languages, you have to define the variable before you can use it. Not true for PHP. We also don’t have to declare data type for variables. But don’t misunderstand, you can’t just mix and match data types and get away with it. PHP does its best to work around your inconsistencies and try to match data types, but it does get confused at times.

Arrays

Arrays are basically a group of variables under a single name. Much like how variables are not strongly typed, the individual elements of an array are not strongly typed and they don’t have to be the same type.

To create an array in PHP you use the array function as follows:

    $arr = array();

This will create an empty array. To create one with values, all you have to do is add them as a comma separated list inside the parenthesis.

    $arr = array(1,2,3,4,5);

To access the elements of an array, you use square brackets with the key of the element you want. Much like other languages, the element keys begin with zero and go up from there by default. Using the above array you will get the following:

    echo($arr[0]); //prints 1
    echo($arr[3]); //prints 4

Unlike other languages however, if you attempt to access an array element that has not been created, PHP will not error out. It will create a Notice and then attempt to do what you wrote. So the following code will still execute, but not what you expect:

    echo($arr[5]); //prints nothing and throws a notice

You can also create an array and define the keys yourself. To do this you use the => operator in you list:

    $arr = array('ARR1'=>1, 'ARR2'=>2,'ARR3'=>3);
    echo($arr['ARR2']); //prints 2

If you want to add an element to an existing array, all you need to do is the following:

    $arr[] = 6; // this adds the value six to the next element in the array
    $arr['ARR4'] = 4; //this adds the value 4 to the element whose key is defined by 'ARR4'

If you want to determine if a $variable holds an array you use the is_array function.

    if(is_array($arr))
    {
        //do something
    }

is_array will return true if what is passed in is an array and false if it is not.

To count the elements in an array you use the count function.

    $var = count($arr);

That returns the total number of elements in the array.

There is a lot of other useful functions that deal with arrays, but this covers the basics. We will discuss more in later chapters.

Constants

PHP, much like most programming languages, allows you to declare constants. These are like variables, but their values do not change. To create a constant you use the define call:

    define(CONST_GREETING, 'Hello');

In the call above, you create a constant with the name of CONST_GREETING. You can give constants any variable type such as Boolean, string, integer or float.

There are a few things to remember, when creating the constant, use a string with no quotes or $. Also, by default constants are case sensitive. This means that CONST_GREETING and Const_Greeting are not the same thing. You can make a constant case insensitive. To do this you pass true as the third parameter:

    define(CONST_GREETING, 'Hello', true);

Now CONST_GREETING and Const_Greeting are the same thing.

If you want to see if a constant has been created and has a value, you use the defined function call. For example:

    if(defined(CONST_GREETING))
    {
        echo(CONST_GREETIONG);
    }

There are a few other advanced concepts around constants, but we will save those for later chapters.

Functions

We have already seen a small example of a function in the section about documentation. Yet, there is still a lot to learn about them. First let’s look at what we saw above with the naming conventions corrected.

<?php
    /*
    This function returns a string with the passed in parameter as part of it.
    */
    function create_greeting($name)
    {
        return "Hello $name";
    }
?>

There are four main parts to a function declaration. Here is what they are:

  1. function key word – this tells PHP that what you are about to write is a function.
  2. Function name – This identifies the function. This will be what the user of the function writes when making the function call.
  3. Parameter list – Inside the parenthesis is the list of parameters that the function needs to operate. You can have anywhere from zero to as many as you need.
  4. Return statement – What your function returns as a result of whatever it does. PHP functions don’t always need a return statement, but they are good practice.

The function key word is required. Without it, PHP will think you are making a function call rather than declaring a function. This will cause an error.

The function name can be anything you want it to be as long as you are not using a reserved keyword or the name of an existing function. If you attempt to use an existing function name, PHP will throw an error stating that you are attempting to redefine an existing function.

The parameter list can consist of any number of parameters of any type. It can contain potential strings, Boolean, numbers or even arrays. You can also declare some parameters to be optional by defaulting them to a value. For example:

    function example_function($param1 = '', $param2 = 0, $param 3 = false, $param4 = array())

In this example, the person calling the function can make the call without passing in any parameters.

It is best practice to place all optional parameters after all mandatory parameters and also in the order they are most likely to be used. An example bad form, but valid, function definition would be as follows:

    function example_bad_function($optional = '', $mandatory)

In this case, someone using this function would have to call the function as follows:

    example_bad_function('', 'Stuff');

It would be better to do the following:

    function example_good_function($mandatory, $optional = '')

With the resulting call:

    example_good_function('Stuff');

Finally we have the return statement. Not all functions require a return statement. But if you do have one, you need to know a few facts.

First, once PHP comes to a return statement, it will stop executing function code. So this means that if you have something you want done in a function, make sure it happens before that call. Example:

    function bad_return_statement()
    {
        return 1+1;
        $var = 1+1; // this line will not run
    }

You can also have more than one return statement and call different ones based on conditional statements. Example:

    function conditional_return($bool)
    {
        if($bool == true)
        {
            return 'True';
        }
        else
        {
            return 'False';
        }
    }

PHP doesn’t really care where in your code tree you declare your function as long as it can find it. You can declare it at the beginning of a PHP file, the end, or even the middle. You can also declare it in a separate file that you include in the file in which you call it. As a best practice, you should keep all functions grouped and out of the middle of files. It makes finding functions so much easier.

Those are the basics of making a function and using them. We will go deeper into functions in later chapters.

Conditional Statements

The next bit of useful PHP knowledge are conditional statements. These evaluate some value and decide on what code to execute based on that value. The two main types of conditional statements are If statements and switch statements. They both function similarly but have their own strengths.

Conditional Operators

In order to use most conditional statements and loops, you will be using conditional operators. These are symbols that evaluate two values and returns ‘true’ if the statement is true or ‘false’ if not.

Here is a breakdown of the primary conditional operators:

== Determines equality

!= Determines inequality

> Determines if the first value is greater than the second

>= Like above but also checks for equality

< Determines if the first value is less than the second

<= Like above but also checks for equality

You can also string together a series of conditions using what are called and and or operators.

And operators are designated as two ampersands ‘&&’ This works by making the condition dependent on both conditions being true.

    if($value < 10 && $value >5)

The above statement will only evaluate to true if the value of $value falls between 5 and 10.

Or operators are designated as two pipes ‘||’ This works by letting either condition return true.

    if($value > 10 || $value < 5)

In the above statement, the statement will evaluate to true if the value of $value is either above 10 or less than 5. However if it fails both, the statement will evaluate to false.

If Statements

If statements test some condition and determine if it evaluates to true or false and executes code based on that result. For instance, if you want to execute one segment of code if the value of a variable equals 3 you would write your if statement as follows:

    if($var == 3)
    {
        //do something
    }

You can also use functions that return true or false to trigger an if statement.

Now let’s say you want to execute one statement when the if evaluates to true and execute a different statement if it evaluates to false. For that, we use an if/else statement.

if($var == 3)
{
    //do something
}
else
{
    //do something else
}

We can also add to this by creating an if/else if/else statement:

if($var == 3)
{
    //do something
}
elseif($var == 2)//you can also use else if (with a space)
{
    //do something else
}
else
{
    //do something else
}

Those are the basics of an if statement.

Switch Statements

Now switch statements are useful when you need to compare a single variable to a list of possible values and execute a different block of code based on each value. You can accomplish the same thing using a series of if statements, but it would require more typing on your part.

To write a switch statement, you do the following:

switch($var)
{
    case 1:
        //do something
        break;
    case 2:
        //do something
        break;
    case 3:
    case 4:
        //do something
        break;
    default:
        //do something
        break;
}

In the above statement, we tell PHP that we want to switch on the value of $var. Depending on what it is, we execute a different block of code. These blocks of code are determined by the case statement.

So if we switch on $var and it has a value of 1 we will step through each case until we hit the one that is checking for 1. Then we execute that code. Once PHP hits that break statement, it boots itself out of the switch.

You will notice that there is no break statement between the 3 and 4 case statements. This is how you would write the statement if you wanted the same code to be executed for more than one possible value.

Finally, we come to the default statement. If the value of $var is not accounted for in the list of case statements, we will execute a default block of code. This can be anything from a lone break statement that boots you out of the switch or some code you want to happen. It is always good practice to have a default statement even if it doesn’t do anything.

That’s it for conditional statements.

Loops

PHP has several types of loops just like any other programming language. These are used to execute a block of code several times without having to write it out that many times. The ability to loop also makes it possible to perform an action when the number of times is variable depending on user provided data for instance.

The main types of loops are: for loops, foreach loops, while loops and do loops.

While Loops

Probably the easiest loop to understand and use is the while loop. The object is simple, while some condition is true, do what is inside the brackets.

Example:

<?php
    $counter = 0;
    while($counter < 20)
    {
        echo($counter);
        $counter++;
    }
?>

In the above example, we start with simple check on the variable $counter. We want to echo out the value of $counter and increment it as long as its value is less than 20. Once the value of $counter hits 20 we will stop entering the loop.

Do Loops

Similar to the while loop, is the do loop. This loop functions much the same with one major difference. The code inside the do loop will always execute once before checking the condition.

This makes it useful if you want something to run at least once but only want tit to execute again if the condition allows.

Example:

<?php
    $counter = 1;
    do
    {
        echo($counter);
    }while ($counter > 0);
?>

The above echo statement will print out once and then the loop will break because $counter is greater than zero.

You will also notice that there is a semicolon after the while statement. This is important. It tells PHP that it is not a new while statement but a part of the preceding do loop.

For Loops

To understand a for loop, we need to look back at the example I gave of the while loop again:

<?php
    $counter = 0;
    while($counter < 20)
    {
        echo($counter);
        $counter++;
    }
?>

You will notice three distinct parts to this loop that controls its behavior. We have the creation and defaulting of a variable. A condition that we must check. Finally we increment that variable, or change its value in some way.

For loops provide a convenient way to combine all three of those steps into a single line. See the above while loop written as a for loop.

<?php
    for($counter = 0; $counter < 20; $counter++)
    {
        echo($counter);
    }
?>

In this example we have all three steps combined inside the parenthesis and separated by semicolons. When we first enter the loop, we create and set a variable to a default value. We then check to see if the condition is met. If it is met, we execute the code inside the loop. Finally, we change the value and check again.

Foreach Loops

Foreach loops are similar to for loops, but are specifically designed to loop through arrays of data. These are best seen in action:

<?php
    $fruits = array('apple','orange','banana');

    foreach($fruits as fruit)
    {
        echo($fruit);
    }
?>

The above code takes and array of fruits and uses the ‘as’ operator to create a new variable of $fruit and executes a block of code using that instance of the variable $fruit. It will continue to loop until you reach the last element in the array.

Foreach loops also have another useful operator the ‘=>’ operation. This is used to create a variable for both the array key and the value of the element.

<?php
    $fruits = array('apple'=>'red','orange'=>'orange','banana'=>'yellow');
    foreach($fruits as $fruit => $color)
    {
        echo(“The $fruit is the color $color”);
    }
?>

Remember, foreach loops will only work with arrays. So don’t even try using it on anything else.

More to come so stay tuned.