Adam - Thu April 2, 2009 11:01 PM

PHP 101-Learn the Very Basics of PHP    

The Big Prologue

The whole purpose of this little tutorial is simply to get you started with PHP. I am assuming a lot of things. For one, I assume you are familiar with building web pages in HTML and using some kind of FTP client. These things are pretty much necessary if you want to tackle a serverside scripting language.

Adsense Ads

If you do know HTML and can wield an FTP editor and even notepad you will do alright. PHP basics really are not that incredibly hard to pick up. As with just about every other programming or scripting tutorial in the world, I will follow tradition by opening things with a “Hello World!” example. Now doesn’t that sound like fun?!

My Hello World Example

I did mention that I’m assuming you know HTML already right? If you don’t, feel free to read along anyway if you wish. The following sentence is my official disclaimer: The HTML you see in these examples may or may not be the right way to use HTML as I’m a bit too lazy in some cases to make sure my example markup is totally valid. I will try to control myself where valid markup is concerned so I don’t somehow distort somebody’s knowledge of HTML(or XHTML if you want to get technical).

This is html<br />
<?php
//This is PHP
echo "Hello Weirdo!<br />";
//This is the end of PHP
?>
this is html again<p>

Well then…you’ve read three paragraphs and learned nothing. Let’s start with the code on the right. It’s a bizarre mix of PHP and HTML. Cool huh?

A file with the extension .PHP or something of the like is nothing more than a glorified HTML file. By glorified I mean that a server with PHP will almost always be set up to look for PHP code in files with these extensions. PHP code can mix within HTML markup. Special tags mark the beginning and ending of PHP code in the HTML. The most common tags are <?php /*This is a PHP comment*/ ?>. These are my personal favorite and what I will use throughout this tutorial. You may also see <? /*This is a PHP comment*/ ?> or <% /*This is a PHP comment*/ %> sometimes.

You may have noticed my last second deviation from the standard “Hello World!” script. What can I say? I’m an individual after all. Back to business…OK so you can mix PHP up in HTML as long as it’s in a file that your server looks in for PHP code. You could do something like the following if you want…

This <?php echo "is"; ?> a <?php echo "sentence"; ?>.
Man <?php echo "I'm"; ?> brilliant!

If you do the above, however, don’t blame me when people start flinging random objects at your head. Take special notice of the word echo in the above code. This is an easy way for you to output HTML from PHP. Take note of the quotation marks around the the words we want to output also. These tell PHP that everything within the quotation marks is part of what you want PHP to output. Letters, numbers and other characters grouped together like this are called strings.

You should also take note of the “;” at the end of each line. The PHP parser needs this to tell it where statements end or it will try to read them as one statement which really makes for some nifty errors. This can be a very common mistake for the beginner.

You can also encase the words in single quotes (or apostrophies if you want to get technical) but there is a difference in the way that PHP handles the string if you do this. We will get to that in the next chunk of this tutorial when we go over variables.

PHP Variables Primer

What in the world is a variable?! Think algebra. The wacky x + 5 = 15 stuff. In PHP it would be something like echo $x + 5;. “$x” would be the variable. If “$x” is nothing then PHP would echo 5. If “$x” were ten then PHP would echo 15. A variable is just a named chunk of memory for you to store information in. Assigning a variable is fairly simple. You could easily use something like var $x=5; or even simply $x=5; would work. If you want to assign a non number to a variable then you need to put it in quotes as a string like we mentioned above. An example would be something like echo “My dog is strange!”;.

Also note that variables begin with a “$” sign. If a variable doesn’t have a “$” then PHP will think it is a constant. We won’t cover constants in this tutorial.

Let’s consolidate some of the stuff we’ve figured out about PHP. The example below is a brief flex of our PHP understanding. There are plenty of things that just aren’t very good practice in it but it does demonstrate some of what you can get away with in your PHP code.

This is html<br />
<?php
echo "This is PHP";echo "This will work too";
$x=5;
var $y=5;
echo $x+$y;
echo "$x+$y<br />";
echo '$x+$y<br />';
echo "X is $x<br />";
echo "Y is $y<br />";
?>

If you run the above code you should get the following output…

This is html
This is PHPThis will work too105+5
$x+$y
X is 5
Y is 5

Confusing? In the line echo “This is PHP”;echo “This will work too”; notice how both echo statements are technically on the same line? This is possible because the afforementioned “;” tells PHP that they are seperate statements. Lines two and three simply demonstrate two different ways to assign variables in PHP. Line four adds the variables together. Notice there isn’t an HTML line break tag at the end of any of these lines. That’s why the output looks terrible

Line 5 is in quotation marks. Remember that this tells PHP that everything within is a string (part of the same group of letters, numbers and other characters). Previously I mentioned that PHP handled strings differently depending on whether they were in quotation marks or apostrophies. When in quotation marks PHP actually parses the string looking for variables. In this case it finds “$x” and “$y” and replaces them with there values which in this case would be “5″.

The next line is the same thing but with apostrophies instead of quotation marks. In this example PHP does not parse the string for variables. It leaves the “$x” and “$y” as they are. In essence, when you encase a string in apostrophies PHP takes you literally. This actually saves PHP some work and increases performance because PHP doesn’t have to parse the string. If you know a string doesn’t need parsed then use apostrophies. In large scripts it may make a notable difference. If it’s too confusing to start with then just use quotation marks if you want. No harm done while you are learning.

In case you are curious about the “+” in lines five and six, it is actually in your quotation marks and is therefore part of a string and not a mathematical operator. PHP replaces “$x” and “$y” with there respective values but the “+” stays as it is. The obvious “5+5″ will remain as “5+5″.

The final two lines again demonstrate how PHP parses strings in quotation marks and replaces variables with their values. We will learn a bit more about variables later on. For now I think we will go into some control structures. Sounds pretty scary huh? Your family might look at you a little odd if you start babeling insanely about control structures, strings and parsing at the dinner table. “Structure” is a good word to use in front of a boss at work every once in awhile though.

If you’re curious to know how one would go about combining strings and variables and more string in an echo statement you’ll find your answer is a simple period. A little vague I know so let’s demonstrate…

<?php
echo $var1." hello ".$var2." $var3";
?>

If $var1=”grand”, $var2=”morning” and $var3=”dog” then the above code will output…

grand hello morning dog

Basic PHP Control Structures

At this point we will add something that will actually allow you to use what you know to make simple, useful PHP scripts. I’m going to call them control structures. There are quite a few handy control structurs in PHP but we will only cover the FOR loop and IF along with ELSEIF and ELSE as this tutorial is supposed to be just the basics. Check out the PHP code below…

for ($variable=0; $variable<10; ++$variable){
echo "output this line!<br />";
}

FOR Loop

The above code is what is known as a loop. The code between the “{}” is a code block. In this case we have a for loop with an attached code block that will execute every time the loop executes. Notice the $variable that we use. This can be anything you want really as the first part, $variable=0;, sets $variable to 0. The next part is the condition for the loop. I will assume you know the greater than and less than symbols from gradeschool(<>). If you don’t then brush up on them as I will not cover them in detail here.

Basically $variable<10; means that as long as $variable is under 10 the FOR loop will continue to execute. The next part, ++$variable, tells PHP to increase $variable by 1 every time the FOR loop executes. So $variable is set to 0 and then we check to see if the loop should go on. If 0 is under 10 then we proceed, adding 1 to $variable which would now make $variable equal to one. We start again asking if $variable is still under 10. If it is then we repeat the previous steps until $variable isn’t less than 10. At that point the code block (code in between the “{}”s) will not be run again. The above code will produce the following output…

output this line!
output this line!
output this line!
output this line!
output this line!
output this line!
output this line!
output this line!
output this line!
output this line!

IF ELSEIF and ELSE

Hopefully you understood the whole loop thing above. We will quickly go over IF, ESLEIF and ELSE. This shouldn’t be too hard to understand if you are still with me and if you do get it then by combining this with variables and the above FOR loop you should have a decent start on really sinking your teeth into PHP.

Check out the code below to help us get a grip on the IF control structure…

if ($variable=="nifty"){
echo "The variable=nifty!";
}

if ($variable<5){
echo "The variable<5!";
}

if ($variable>10) echo "Over ten!";

if ($variable!="nifty"){
echo "It isn't nifty!";
}

Just as in the FOR loop examples everything between the “{}”s is a code block. In these cases the code blocks are only executed by PHP when the conditions of the IF statement are true. In the first IF statement if $variable is equal to nifty then the condition is true and the code block is executed. The reason for the double “=” in the condition is that in PHP the “=” sign is for assignment where the “==” is for comparison. The statement if ($variable=”dog”) echo “dog!”; will always be true because it sets $variable to “dog” in the IF statement instead of comparing the two with “=” as it should. This is a common mistake for someone new to PHP to make. You will get used to finding and fixing this mistake in your code as you progress.

You probably recognize the greater than and less than symbols (”<>”) from before but you you recognize the “!=” in the last IF statement? I snuck this one in as it is a very handy operator. “!” basically means “not” so “!=” means “not equal to”. This statement is true only if $variable isn’t equal to “nifty”.

In the third IF statement you probably also noticed that there are no “{}”s around the code. If the code you want executed for an IF statement is only one line then you can tack it onto the end of the statement. The easy way to understand this is to note that there isn’t a “;” after the above code blocks. PHP knows that the line after a code block is seperate from the code block already because it isn’t in the code block. PHP always needs something to do if your condition is true though. If you can do everything you need to do on the same line with the IF statement then a code block isn’t necessary. The “;” tells PHP that the IF statement has ended and the next line will begin a new statement.

Conclusion

Put all of this together and you should have a good start. This tutorial was meant as a starting point. Look up other tutorials that you can understand and make sure to check out the links in the resources box on this page. I hope this was helpful to someone. Keep checking back as I am constantly adding new tutorials and such.

Leave a Reply

You must be logged in to post a comment.