You are using a browser which is not compatible with CSS (for more information, see Tara's tutorial). Because of this, it is possible that our website may not appear correctly in your browser. We apologise for the inconvenience, and recommend you upgrade your browser to one which is compatible with CSS. For more information, please visit our Browser Upgrade page.

4WebHelp

PHP Extreme Basics by Adam

Last updated: 02/05/2012
Biography: Adam is currently a student at Brooke Weston CTC in the UK, learning many aspects of computing in his spare time. Things which he is currently learning include PHP, C++ and how to use the Linux Operating System. He first starting exploring HTML several years ago, and has also been working with PHP for almost as long. He is also sometimes known as Odhinn.

Introduction

This tutorial is for people who have never used PHP before. I'll be dealing with the absolute basics; the things you'll need to use in almost every PHP script you write. I'll mainly be using non-technical language, so don't worry if you're completely new to programming - I'll go easy on you!

The Basic Layout of a PHP File

Below is an example of a PHP script:

<?php
include('header.php');
?>
<p>Welcome to my web site!</p>
<?php
include('footer.php');
?>

That is a very basic example of the use of PHP. The actual language used is not important at this stage; it's the structure that I want to talk about. On most servers, every PHP file must begin with <?php (or <? if short tag is enabled - however this is becoming less and less common, as short tags have to be off on any server which supports XML: <?xml). This is what tells the PHP program (or parser) that the code that follows is PHP. At the end of your PHP code, you should put ?> (not php?>).

Generally speaking, each line of code must end with a semi-colon (;), this is so that the parser knows where one bit of code (or statement) ends and the next one begins. There are many kinds of statement, they will all be covered within this tutorial. But first, lets talk about variables...

Variables

If you've used any programming language before, or even if you took algebra in school, you should know what a variable is. A variable is a string, or group, of characters which have some kind of value. For example, the variable $apple might have the value "green". You might be wondering why you just couldn't write green instead of using the variable. The answer is simple: you might want to include the value of the variable several times in your code, certain parts of the code might even depend on the value of the variable. It may even be necessary to change the value of the variable while the script executes.

Note to users of other languages: You might be used to using different types of variables, e.g. char and int, in PHP this is not necessary. All variables are the same. Also, you don't have to define variables before you give them a value.

Now that you know what a variable is, you might be wondering how exactly you use them. The below example shows how you assign a value to a variable and tell the user that value.

<?php
$variable = 'cuo.org.uk';
print 'Don't you agree that '.$variable.' is great?!';
?>

This particular example, by itself, is useless. But it does show clearly how to use variables in simple situations.

You should note that there are some variables that you cannot use, click here for a list of the variable names you cannot use. Also, variable names must start with a letter or an underscore ( _ ), and they can only contain letters, numbers and underscores. One more thing, the names of variables are case sensitive, so $var is different to $Var.

Functions

Basically speaking, a function performs a set of statements. As with variables, there are pre-defined functions and you can create your own. Creating your own functions can come in handy when there are things that you will need to do more than once; instead of copying and pasting your code you can just create one function. This not only reduces the amount of disk space you will use, but it will also make it easier to fix errors (errors can be, and often are, copied and pasted).

You have already seen functions in this tutorial. Examples are include() and print(). All functions, except for print and echo, are followed by parentheses. Within these parentheses you can put arguments that will be used by the function in some way. There can be any number of arguments, and they can be variables or strings. Each argument is separated by a comma (,). However, you cannot give a function more arguments than it was written to have, this will cause an error.

Defining (or making) your own functions is very easy. Take a look at the below example:

<?php
function adamsFunction($arg1, $arg2, $arg3) {
print 'The first argument was: '.$arg1.'\n';
print 'The second argument was: '.$arg2.'\n';
print 'The third, and final, argument was: '.$arg3.'\n';
}
$name = 'Adam';
$greeting = 'hello!';

adamsFunction($name, 'BOO!', $greeting);
?>

The output of this script would be:

The first argument was: Adam
The second argument was: BOO!
The third, and final, argument was: hello!

Hopefully you can see how that works, if not go take another look!

The same rules that apply to variable names apply to function names. Also, if you try to use (or call) a function before it is defined, you will get an error and your script will not execute.

Loops and If Statements

Have you, for example, ever created a form on a web page where people are required to enter their date of birth? If you're anything like me, you would want them to select all the options (day, month and year) from a drop-down menu. However, it would be very time consuming, not to mention boring, to have to go and type all those numbers. Wouldn't it be great if there were some way of producing all those numbers without every typing them?

Well, lucky for control freaks like us, there is! Welcome to the wonderful world of loops. Loops are control structures, what that means exactly isn't important at this stage, just remember that loops are very useful and easy. What a loop does is simple: it evaluates an expression, if the expression evaluates to true it performs one or more statements then repeats. If the expression is false, the loop ends.

The main two types of loop you are likely to encounter are while and for. First, I'll explain the simpler of the two; while.

while (expression) {
   statement
}

This kind of loop is so simple it hurts. If expression is true, statement will be run. At this point, you're probably scratching your head wondering "What will make expression true and what will make it false?"; Well, it's funny you should ask.

Most often the expression will be some combination of strings and variables, separated by some kind of operator. That may sound complicated to you at first, but trust me it's not. Take a look at the below example.

while ($n == 3) {
print '$n is 3';
}

Why anyone would use a loop like this is beyond me, but it gets the idea across. If $n equals 3, the expression $n == 3 will evaluate to true, if it doesn't it'll be false. At this point you may be wondering why in the above expression I used two equals signs instead of one. The reason is that if I wrote while ($n = 3) the expression would always evaluate to true. Why? you might ask. Well, the expression $n == 3 compare $n and 3, but the statement $n = 3 makes $n equal 3. Get it? Good! Make sure that in all loops and if statements you don't get that confused. I say that, but if you're reading this you're probably pretty new at this, so you will make the mistake of writing one equals instead of two. Hell, I used to do it all the time! At least you know what to look for.

Anyway, back to our example. In case you didn't already realise, the loop in this example will go on forever, or never execute. It will never stop, because $n never changes; so if it equals 3 the first time it always will. That's why normally you will change whatever is being evaluated at some time during the loop - I've never found it to be the case that an infinite loop is useful.

Note to linux users: Type "yes" at your terminal to run what is quite possibly the most useless program ever made. I'm not sure if all distributions have this program, but I do know that Red Hat 7.1 does.

Now, onto the second type of loop; the for loop. This kind of loop is slightly more sophisticated than a while. Take a look:

for (Beginning statement; expression; Ending statement) {
   statement 
}

There are two extra things there, as I'm sure you noticed, being the keen observer that you are. The Beginning statement will be run at the start of the loop, the expression will be evaluated each time the loop is repeated as with while and the Ending statement will be run at the end of each iteration (each time the loop is repeated). This kind of loop is useful, for example, when you want to easily (with as little code as possible) do something a certain number of times. The below example will print (display to the user) the numbers 1 through 10, each on a new line.

<?php
for ($i = 1; $i < 11; ++$i) {
print '$i\n';
}
?>

I'll explain the new parts of the code in a second, but first here's the while example:

<?php
$i = 1;
while ($i < 11) {
print '$i\n';
++$i;
}
?>

As you can see, the for loop is far simpler. It uses less code, which is always a good thing. Now, you may be wondering what some of that code does, so I'll tell you. The statement $i < 11; means, in English, $i is less than 11 - it's a standard mathematical symbol (there's a list of the most commonly used symbols, or operators, at the end of this article). You're probably also wondering what this strange \n is. All that does is print a new line, in the same way that \t prints a tab. There is a list of these at the end of the article, but right now there is no explanation - that will be in a later article. One other thing you may not recognise or understand is ++$i. Basically, all this does is increase the value of $i by one.

Note: You can also use $i++. The difference between that and ++$i is not important right now, but will be explained in a later article.

So, to sum up for loops, the above example will do this:

Give the variable $i the value of 1.
Check $i is less than 11.
If it is, print $i. If it isn't, do nothing and go no further.
Increase $i.
Check $i is less than 11.
If it is, print $i. If it isn't, do nothing and go no further.
Increase $i.

... and so on.

Now that I've given you an introduction to the wonderful world of loops, lets move on to something else...something that's similar, just as useful and even simpler than loops. I'm talking about If Statements. You are likely to use If Statements very often, believe me, so it's probably a good idea to get used to them now. Now that I think of it, the same goes for loops.

So, you're probably wondering: What the heck is an If Statement?! Well, the answer is simple: An if statement is a control structure that will perform a set of statements only if a certain expression is true. "Wait a minute!" I hear you scream. "Isn't that what a loop does?!" Yes, that is what a loop does, but an If Statement will only do it once - a loop can do it any number of times repeatedly. Let's dive right in with an example: I want to print a welcome message, but only if the variable $name is "adam". This is how it would be done.

<?php
if ($name == 'adam') {
print 'Hello Adam';
}
?>

Exactly where $name comes from is not important, it could some from anywhere - it doesn't matter. This script would give the message "Hello Adam" (minus the quotes, of course) if $name is equal to "adam". If $name doesn't equal "adam", in this example nothing will be done.

That in itself is pretty useful. But what if you want to give another message for all the non-adams out there? There are a number of ways you could do this. You could write another separate If Statement, with $name != 'adam' as the expression, without having to learn anything new. There is, however, a slightly better way:

<?php
if ($name == 'adam') {
print 'Hello Adam';
}else{
print 'You're not Adam! Go away!';
}
?>


What this does should be pretty obvious. The else part of the above will print the other message if $name doesn't equal 'adam'. There's also something else you might like to do. What if you wanted to give personal messages to more than one person? It's possible, and it's easy. "How do I do it?" You may say. Well, it's funny you should ask:

<?php
if ($name == 'adam') {
print 'Hello Adam';
}elseif ($name == 'bob') {
print 'Bob! How are you?';
}else{
print 'You're not Adam or Bob! Get outa' here!';
}
?>

elseif allows you to do something if the all the previous expressions evaluated to false, and if the current one evaluates to true. There is no limit to the number of elseifs you can use. Now you should, hopefully, see the power of If Statements. They give you complete control over your script, and they are very, very useful when combined with loops.

Appendix A - Operators

Arithmetic Operators
Addition: $a + $b
Subtraction: $a - $b
Multiplication: $a * $b
Division: $a / $b

Comparison Operators
Equal: $a == $b
Not equal: $a != $b
Less than: $a < $b
Greater than $a > $b
Less than or equal to:$a <= $b
Greater than or equal to: $a >= $b

Incrementing/Decrementing Operators
Pre-increment: ++$a
Post-increment: $a++
Pre-decrement: --$a
Post-decrement: $a--

Logical Operators
Not: !$a
And: $a && $b
Or: $a || $b

Appendix B - Escape Sequences

\n Newline
\r Carriage Return
\t Tab
\\ Backslash
\" Double quote

© 4WebHelp and Adam

This work, originally published as "PHP: Extreme Basics", is distributed under the terms of the cuo.org.uk Copyleft Policy 1.0, a copy of which can be found at http://www.cuo.org.uk/.

Latest comments on this tutorial
Nomi
I liked it.  But I'm fluent in VB, and am moving into html.  I'm trying to figure out if I can use PHP instead.  Maybe because I already know a bit of programming I found this to be useful.  It's not much, just an idea, but just enough to encourage me that this might not be so hard Smile
brisn
basics. NO

Computer programmers need to look up the word in the dictionary.

I have been making web pages for years, but when I read this "basic" page over i got lost REAL quick.
Shell
People can certainly be ungrateful can't they? This is a great tutorial, thankyou so much for taking the time to put it together it's been so helpful Smile
Jgj
Adam, I just wanted to say thank you for taking the time and trouble to put this very educational article together, it's guys like yourself who make browsing the 'Net worthwhile.
I'm really glad I found this site and in my doing so it's made me even more determined now to learn php.
HxD
Sigh, if u want anything to happen just try some stuff out, search for it @ google. And I must say, these things, are basic alright..

Cheers.
David
Well i agree with the other guy this isn't the very very basics.i have a php book that starts somewhere in the middle of everything.but i did learn something about functions lol thanks Very Happy
AskCy
I'm just looking at doing some PHP to help make my site easier to change. Create a standard set of instructions through it and then just alter the variables..

now the last time I did any real programming was on a ZX Spectrum so I was looking at the basic basic start of php...

I have PHP on the server and can upload php files to it.

I also have a reasonable knowledge of HTML )and can copy and alter things that are already done)

BUT this is all moving to fast... the 2 basic instruction page both conflict with <? saying use this and then <?php use this and jump straight into arrays and variables..

I was told that PHP can be made to creat HTML pages just as if it was HTML only you can add variables and things that change...

Now I think I need BASIC's telling me how to put a heading on a page, how to center it, how to make it bold.

No stop laughing, to you its obvious but I don't know how php does it?

For example if I wanted to put a simple heading in the middle of a page using PHP would it be like this ?

<?
echo "<center><h1>My Heading</h1></center>"
?>

This is the Basics I think I need, then I could move on to replacing that heading with a variable if thats how it works..

Thanks for helping us out !
Jon
I wouldn't call this the very basics!  The basics would be what you need to get started and where to get it from.  Also it should take you through 1 example page.  

Im looking to start with PHP and this hasn't really taught me what i need to know!

Add a new comment

This page is © Copyright 2002-2017, 4WebHelp. It may not be reproduced without 4WebHelp's prior permission.