PSBailey.co.uk - homepage

PHP Part 2 — Crash Course


Welcome back, to part 2 of the series. Hopefully by now you will have read part 1, and gained an understanding of what PHP is, and it’s potential. From here on in, it’s coding all the way, so let’s get stuck in. I will not attempt to cover everything in PHP, just the parts that are likely to be most useful to you in the real world. The best way to get to grips with what you’ll learn in this article is to try it out yourself, play with it and see what works and what doesn’t. Today’s lesson is a lot to take in, and there may not seem to be a lot of gain at first, but if you “get” this lesson, the next one will have you feeling like an expert and really using PHP as it should be used. We’ve still got a long way to go, but the learning curve gets a little less steep after this one. Hang in there, it’ll be worth the hard slog.

Embedding PHP in HTML files

With PHP, it’s simple to place dynamic content directly into an existing HTML framework. The best way to show this is with an example:

<html>
<head>
  <title>Test Page</title>
</head>
<body>
  <h1>Welcome to my page!</h1>
  <?php
    echo '<p>Hello World</p>';
  ?>
</body>
</html>

The source output of this would look something like:

<html>
<head>
  <title>Test Page</title>
</head>
<body>
  <h1>Welcome to my page!</h1>
  <p>Hello World</p>
</body>
</html>

Quite easy really. You’ve now met your first (and one of the most used) PHP commands: echo. Echo basically takes everything you put in a string, and outputs it to the browser. You can use the word print instead of echo if you like, they do the same thing but echo is the tiniest bit quicker. Use whichever one you feel most comfortable with. Echo should be used sparingly, if you find that you are using echo to output whole large sections of plain HTML, consider rewriting your code. Do not be tempted to do this, as it’s a complete waste of your server’s time as it could just be left as plain HTML:

<?php
echo '<html>';
echo '<head>';
  echo '<title>Test Page</title>';
echo '</head>';
echo '<body>';
  echo '<h1>Welcome to my page!</h1>';
  echo '<p>Hello World</p>';
echo '</body>';
echo '</html>';
?>

Another EXTREMELY important thing to note in this is the semicolon (;) character at the end of the line of PHP. You MUST put this at the end of any line that executes (like this one, which executes echo) or assigns (see variables below). If you don’t do this, your PHP script will error, and say that there was an error on line X, where X-1 is the line you missed the semicolon from. You have been warned, this is one of the biggest sources of errors for first time PHP coders.

As mentioned in the first article in this series, you may use the normal <?php tag, or the short <? tag for PHP. Throughout the series, I will use the longer version as it is the most universally supported version.

Whitespace

PHP treats whitespace exactly the same as HTML does, it ignores it. Therefore the following three snippets are identical. You should choose the one that is easiest for you (and anyone else who is likely to edit your code) to read. Hopefully you’ll agree that the first example is best:

echo 'hello ';
echo 'world';
echo 'hello ';echo 'world';
echo 'hello ';            echo 'world';

Moving Swiftly On ... Comments

As you are no doubt a seasoned HTML slinger, you’ll be aware that sometimes it’s good to add comments to your code. In HTML you would do it like so:

<!-- My comment here -->

In PHP, there are two ways to comment your code:

<?php
//this is a one line comment; note the 2 slashes at the start
echo 'This line will echo as normal';

/*
This is a multi-line comment.
Everything in here will not get sent to the PHP parser, or to the browser of the site
...so the next line will not echo anything...
echo 'Something that will not print';
Let’s end the comment now, the opposite way it starts, with an asterix then a slash.
*/
?>

Variables

Without variables, PHP would be virtually useless. A variable is a named object that can hold a piece of text or a number within it. You can then use this data later on when you need it. Variables are usually available to the whole PHP/HTML file they are declared in, except in the case of functions, which we will cover in later lessons. PHP variables begin with a $ sign, and then have the name you give them. They are also case sensitive, so $MyVariable is not equal to $myvariable. Here’s an example:

<?php
//We will use these variables later on
$myvariable = 'Hello World';
$theweather = 'Cloudy';
?>
<html>
<head>
  <title>Test Page</title>
</head>
<body>
  <h1>Welcome to my page!</h1>
  <?php
    echo $myvariable;
    echo '<br/>';
    echo 'The weather today is: ';
    echo $theweather;
  ?>
</body>
</html>

This will display as follows (note the PHP comment never shows up):

<html>
<head>
  <title>Test Page</title>
</head>
<body>
  <h1>Welcome to my page!</h1>
  Hello world<br/>The weather today is: Cloudy
</body>
</html>

You can tidy up this code a little, by using a dot operator to add lots of strings together before they get echoed:

<?php
//We will use these variables later on
$myvariable = 'Hello World';
$theweather = 'Cloudy';
?>
<html>
<head>
  <title>Test Page</title>
</head>
<body>
  <h1>Welcome to my page!</h1>
  <?php
    echo $myvariable.'<br/>'.'The weather today is: '.$theweather;
  ?>
</body>
</html>

PHP takes $myvariable, adds a break tag to end of it, adds “The weather is: ” to that, and finally adds “Cloudy” to them all, and then the whole lot is echoed.

Variable Types

PHP is a loosely typed language, so you do not need to define what type a variable is when you create it. If you want to create a number, use $myvariable = 1; If you want a string, use $myvariable = '1'; There are ways to turn numbers into strings and back again, but as a variable’s type is not set in stone, you should rarely need to use these methods. PHP will often do the conversion for you. For instance, if you want to add a number and a string:

<?php
$x = 123; //this is a number
$y = '4'; //this is a string

//PHP will turn both into strings, and return “1234”.
echo $x.$y;

//PHP will turn both into numbers and return 127.
echo $x+$y;
?>

Single Vs. Double Quotes

There really is no better way to tell you this than with a demonstration, so here goes:

<?php
$myvariable = 'Hello World';

//this will output "$myvariable, how are you today?"
echo '$myvariable, how are you today?';

//this will output "Hello World, how are you today?"
echo "$myvariable, how are you today?";

//this will also output "Hello World, how are you today?"
echo $myvariable.', how are you today?';
?>

Any variables contained in double quotes are returned as their value, while those in single quotes are just left as-is. This is particularly important for Americans who want to echo a $ symbol without PHP trying to turn it into a variable, but it does raise a point: which way is better, dotting a load of single quoted strings, or inserting your variables into a double quote string? Personally, I prefer to use dotting, as then the PHP processor does not have to parse the whole string, just chuck the single quoted bits straight out. In theory, this should be marginally quicker than the double quote method. In practise, you’ll come across times when either one might be best. It’s your call.

Operators

Operators are the most basic nuts and bolts of PHP. You have already come across at least three of them already in this article, =,+ and the dot operator (.) (also known as the string concatenation operator). We’ll now cover all of them in detail, starting with arithmetic operators.

Arithmetic Operators

These are the basic mathematical operators, and there are 5 of them:

Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

All of these can be used as follows:

<?php
$a = 4;
$b = -1;

//sets $c to be the value 3
$c = $a + $b;
?>

The first four operators should be clear to most, but the modulus operator might not be so obvious. This is the remainder when one number is divided by another. so 45%12 would be equal to 9, as 12 goes into 45 a total of 3 times, with 9 left over. In PHP this is:

<?php
$a = 45;
$b = 12;

//This will output the number 9.
echo $a%$b;
?>

The Assignment Operator

This is just a posh way of say the equals sign. You should always think of this as “becomes set to”. I’ll say that again: “becomes set to”. So $x = 10; means “the variable called x becomes set to 10”. In a short while we will cover something called the equals operator, which seems almost the same, but is radically different, and so it is vital that you realise what = means. You have already seen how the assignment operator works, so I won’t cover it again, see some of the examples above if you are still a little hazy. One interesting thing about it though is that is that it returns a value of itself, so you can do things like this:

<?php
//This set $x to 57, and $y to 12
$x = 45 + ($y = 12);
?>

Remember ye well this little snippet of code, because when we get to the aforementioned equals operator, this will rear it’s ugly head again. If you take this in (and keep saying “becomes set to”), you will save yourself months and weeks of banging your head against the wall wondering what the hell is wrong with your code.

String Operator - The Only One

The dot operator (.) is the only string operator, and we have already used it several times, so I won’t cover it again. As long as you know it works only on strings, that’s all that matters.

Shorthand Operators

This group of operators aren’t really proper operators, they’re shorter ways of using other operators when you need to change the value of a variable you already have.

Operator Example Equivalent to
+= $x += $y; $x = $x + y;
-= $x -= $y; $x = $x - y;
*= $x *= $y; $x = $x * y;
/= $x /= $y; $x = $x / y;
%= $x %= $y; $x = $x % y;
.= $x .= $y; $x = $x . y;

Here’s some examples:

<?php
$x = 4;
//This sets $x from 4 to 9
$x += 5;

//This sets $x from 9 to 8
$x -= 1;

//This sets $x from 8 to 24
$x *= 3;

//This sets $x from 24 to 12
$x /= 2;

//This sets $x from 12 to 2
$x %= 10;
?>

Comparison Operators

There are eight of these, and one is so important I will give it special attention in a second. First though, here they are:

Operator Name Example
== equals $x == y
=== identical to $x === y
!= (you may also use <>) not equal to $x != y
< less than $x < y
> greater than $x > y
<= less than or equal to $x <= y
>= greater than or equal to $x >= y

All of these will return true or false when comparing two items, and are usually used in if statements and the like, which we will cover in later lessons. Of all of these, the equals operator (==) has the most potential for destruction. It looks a little too like the assignment operator (=) we covered earlier. If you are finding that your test always returns true or always returns false, even when it shouldn’t, it’s because you have used the assignment operator when you should have used the comparison operator!!!! Never ever forget that, it is a logic error in your code, and virtually impossible to find unless you keep that in the front of your mind at all times. Remember, = means “becomes set to”, == means “is already set to”, and is either true or false.

The identical operator is like the equals operator, but they must also be of the same type. For instance, false == 0 returns as true, but false === 0 returns false (false = 0 and true = 1 in binary, so they are kinda the same, but not *exactly* the same).

Pre- and Post- Increment and Decrement Operators

These take a little bit of getting your head around at first, but are extremely useful when you are dealing with numbers. Consider the following examples of the Incrementer (++):

<?php
$x = 4;
$x++; // $x is now equal to 5
++$x; // $x is now equal to 6. These are not the same though, look at this...

echo ++$x; // echoes 7
echo '<br/>';

echo $x++; //echoes 7 again! This is because it echoes $x first, then adds one to it.
echo '<br/>';

echo $x; //echoes 8! The last $x++ added one, but didn’t show it straight away!
?>

The Decrement operator works in the reverse way, it uses -- and subtracts one.

The Reference Operator

This is new as of PHP4, and the fact that people survived for so long without it shows how it’s not the most useful operator in the world. It allows you to update several variables to the same value at once, but most of the time then you should only need one variable. I’ll cover it briefly, with these examples:

<?php
$x = 4;
$y = $x;
// $x and $y are now equal to 4

$x = 10;
//$x is now 10, but $y is still 4, oh no!
//In the old days you would just update $y again manually.
?>
<?php
//Now you can do this
$x = 4;
$y = &$x;

$x = 10;
//This has updated both, as $y has been set to just point
//to the value in $x no matter what.
?>

Logical Operators

These are used when you need to combine two or more of the reference operators.

Operator Name Example
! not !$x
&& and $x=1 && $y=0
|| or $x=1 || $y=0
and and $x=1 and $y=0
or or $x=1 or $y=0

Form the table, some of the operators seem to be the same, but not quite. || and && are more important than and and or, so if you use them together the || and && will be evaluated first. ! returns the opposite of what it is in front of, so if $x = true, !$x is false.

The Error Suppression Operator

Suppressing errors that might arise in your code can sometimes be very handy, but you should try and code around them, rather than hiding them. Nevertheless, there is a way to hide an error if you really must, try and use it as a last resort.

<?php
$x = 10;
$y = 0;

/*
This gives a big error message!
Division by zero is not mathematically allowed.
Try it out on a calculator if you don’t believe me...
*/
$z = $x/$y;

/*
Try this instead, no error because we used the error suppression operator (@)
Ideally you should make sure you never divide by zero by testing $y first.
Try and spot errors before they happen, rather than hiding them.
It’s the sign of a good bit of code if errors are dealt with,
rather than swept under the carpet.
See the example below if you’re curious...

*/
$z = @($x/$y);

/*
How to handle this error in a much nicer way...
We will cover if...else statements in the next lesson,
this might not make sense at the moment.
*/
if ($y == 0) {
  echo '<b>Terribly sorry about this lads...</b><br/>';
  echo 'Sorry, could not do the division because y is equal to zero.';
} else {
  $z = $x/$y;
  echo $x.' divided by '.$y.' is equal to '.$z;
}
?>

Other Operators Not Covered

I will not cover the ternary operator, the execution operator or the bitwise operators as you will be unlikely to need them until you become a PHP guru. The ternary operator is a shortened version of an if...else command that will only be appreciated by real PHP nerds like myself who you might show your code to, the execution operator executes system commands on the server, and the bitwise operators perform binary comparisons. Operators for PHP nerds, nuff said.

The Order They Go In

There is a precedence that decides which one of these operators gets tested first. Here’s the table, the nearer the top an operator is the more important it is:

Operator
( ) brackets
! ++ -- @
* / %
+ - .
< <= > >=
== != ===
&&
||
= += -= *= /= %=
and
or

There are other operators, but these are the main ones we will cover. These are important because of things like this:

<?php
//returns 14, as the * is more important so gets done first
$amount = 10 * 1 + 4;

//returns 15, as everything in brackets gets done first
$amount = 10 * (1 + 4);
?>

So What Have We Learned?

Today you will have taken your first steps into PHP, and maybe even programmed a few basic examples. There was a lot to take in this time, with seemingly not much gain, but in the next lesson we will put all these skills to the test by creating a simple online order form. We will also pick up a few extra bits of code that will get you well on your way to being able to build your own sites.

Get Firefox! Valid XHTML Valid CSS