The absolute basics of PHP

July 24th, 2009 in PHP, Tutorials
php

PHP is a hard language to master and sometimes you just need a little push to get started. Thats why I put together this (very) basic guide on everything you’ll need to know to get started in PHP





PHP is one of the webs favorite server side programming languages. It’s used all over the web. In this introduction I will help you learn the absolute basics to PHP. I want this to be a complete walkthrough to starting out in php, so if you’re a bit more experienced I don’t think this tutorial will really benefit you.

Starting off with PHP

All PHP documents begin with <?php, and end with ?>. These are just a way to tell the web page that the php part of the document has begun (<?php) and it has ended (?>).

1
2
3
<?php
 
?>

You can mix PHP with HTML, so you could have something like this:

1
2
3
4
5
<strong>
<?php
 
?>
</strong>

PHP files usually have the extension .php.

Showing Data with PHP

There are many ways to show data inside php. Usually, when showing data we’ll do the following:

1
2
3
4
5
<?php
 
echo"Data goes here, this can include html, etc.";
 
?>

As you can see it’s pretty straight forward. We can also use “print” instead of “echo”, if we wanted to. However, for the time being, lets stick with echo. Another thing I should mention at this point is that each PHP line ends with a semi-colon (;). This denotes the end of the line. You must include this, otherwise your script wont work.

Comments

Comments are a way of displaying some information for the coder, without altering the overall code. These allow you to place information on the script so you remember what each part does, which is quite useful in huge scripts. There are two ways to comment on a script. You can either use two forward slashes, or a forward slash and a star. Here’s the example:

1
2
3
4
5
6
7
8
9
10
<?php
 
// Hello, I'm a comment. However, I only work for one line, so if I want to do another comment on the line
// below I have to do another two forward slashes.
 
/* Hello, I'm another comment. I'll comment anything thats in front of me
    until i see myself backwards.
*/
 
?>
Storing data

In PHP there are two key ways to store data (well, unless you have a database): arrays and variables. Lets start with variables as that’s the easier one.

1
2
3
4
5
<?php
 
$variable = "value";
 
?>

Okay if you’ve never used PHP before the above may look confusing, but let me try and explain it to you. the dollar sign denotes the start of a variable. The bit after the dollar sign is the name of the variable. This can be anything you want. The bit in speech marks is the value which you want to assign to that variable. Think of it like this: $variable has became equal to “value”. Therefore, we can use $variable instead of value. For example, if we were writing a sentence, such as: “The value of the diamond was high”, we could instead write “The $variable of the diamond was high”. This is exactly how php works with variables. For example, if we had the above, we could echo it out at one point as shown below:

1
2
3
4
5
6
7
<?php
 
$variable = "value";
 
echo"The $variable of the diamond was high";
 
?>

This will show: “The value of the diamond was high”. It should also be noted that you don’t have to use speech marks in echo if you’re just showing the variable:

1
2
3
4
<?php
$variable = "value";
echo $variable;
?>

Now lets say we have two variables, and we want them to appear as a sentence. For instance, I have these two variables:

1
2
3
4
<?php
$variable = "i like to";
$cow = "drink milk";
?>

To do this we use a dot, with the echo function, as shown below:

1
2
3
4
5
6
<?php
$variable = "i like to";
$cow = "drink milk";
 
echo $variable." ".$cow;
?>

The dots are just there to merge the variable with the space, and the other variable. However, let’s move on.

Arrays are incredibly useful, and are something I use a lot when coding. There are many ways you can make an array in php, but the most basic way to do it is as follows:

1
2
3
4
5
<?php
 
$array = array('value', 'orange', 'pineapple');
 
?>

Imagine an array as a way to define loads of variables at once. I’ve put this array in a variable as it’s more useful this way. To show a certain part of an array we use square brackets. Each part of an array is assigned a number, so we can say that ‘value’ is number 0, ‘orange’ is number 1, etc. That’s how we differentiate between them, so lets say you wanted to show only the word “orange”. To do this, you would do the following

1
2
3
4
5
6
7
<?php
 
$array = array('value', 'orange', 'pineapple');
 
echo $array[1];
 
?>

The number in the square brackets is the id of the value you wish to show (or manipulate). These numbers are often referred to as keys. It’s possible to change the key if you want, by doing the following:

1
2
3
4
5
6
7
<?php
 
$array = array('a'=>'value', 'b'=>'orange', 'c'=>'pineapple');
 
echo $array[a];
 
?>

The above would output the word “value”, since it now has the key “a”. In arrays there are two key functions that I use all the time: explode and implode. Explode takes a string and turns it into an array, and implode takes an array and turns into a string. Let me show you an example of explode firstly:

1
2
3
4
5
6
7
<?php
 
$variable = "some people might think cows like to drink milk";
 
$array = explode(" ", $variable);
 
?>

As you can see, explode has two conditions set, separated by a comma. This is usually how functions work in php, with different settings being separated by a comma. The first part of explode, where I have put ” ” (a space), is the delimiter. This is what we want the array to be split up by. The second part is the string, which is what we want to turn into an array. Therefore, this will make a new array, with a new item being started for every space, i.e. “some” would be key number 0, “people” would be key number 1, etc. Implode does the exact opposite of this, as shown below:

1
2
3
4
5
6
7
<?php
$variable = "some people might think cows like to drink milk";
 
$array = explode(" ", $variable);
 
$implode = implode(" ", $array);
?>

This will turn the array back into what it was originally: a string. The first part of implode is what you want to separate each item in the array by once its turned into a string. The second part is the array you wish to turn into a string.

If, Elseif, else

Statements are ways of making something happen if something else is true or false. The most basic statements are the if, elseif, and else statements. Here’s an example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
 
$variable = "1";
 
if($variable == "1") {
     echo"The value of the variable is 1";
}
elseif($variable == "2") {
     echo"The value of the variable is 2";
}
else { 
     echo"The value of the variable is neither 1 or 2.";
}
 
 
?>

Hopefully you understood that. Think of it as you think of regular, everyday language. the double equals sign means “is equal to”. so by saying if($variable == “1″) {, you’re basically saying if $variable is equal to 1, then... The { curly bracket denotes the start of what you want to happen if the statement is true. Likewise, the } curly bracket denotes the end of that section. Elseif works exactly the same as if, except it’s what’s going to happen if the if statement returns false (the variable is not equal to 1). It also has a condition. In this case we’re checking to see if the variable is equal to 2. Finally, else is what happens if all else fails. That about covers if, elseif and else.

While, foreach and for

Okay, lets start with while. While is the most basic loop you can have. Here’s an example of a while loop.

1
2
3
4
5
6
7
8
9
<?php
 
$i = 1; 
 
while($i < 50) {
     echo"$i <br />";
     ++$i;
} 
?>

Okay so this might look a bit complicated, but lets think about it. What we’re saying is $i is equal to 1. Then we have a while statement. What this line is saying is, while $i is less than 50, then show the number (with a line break) and increase $i by 1. The ++ in front of $i just means increase by one. Unlike the if statement, the while statement will keep happening until $i is not less than 50. If we didn’t increase $i by 1 with the ++ operator, this would cause an infinite loop, which we don’t really want. There is also do-while, which works the same, only the condition is at the end:

1
2
3
4
5
6
<?php
$i = 1;
do {
     echo"$i <br />";
} while($i < 50) 
?>

You’ll see that it works very similarly to while.

for is another loop, which works in a much more complex way. We’re going to do the exact same loop as before, only if it was for, instead of while:

1
2
3
4
5
6
7
<?php
 
for($i = 1; $i < 50; ++$i) {
     echo"$i <br />";
}
 
?>

Using for we’re able to put all conditions in the brackets beside for, as shown above. Each part in the brackets, is separated by a semi colon. The first part defines the variable, the second part is the condition, and the third part is what you want to happen if the condition is true. Then the bit in the curly brackets is just what you want to show on screen.

Finally lets cover foreach. Foreach is another way to modify arrays. Basically what it does is takes an array and turns its key and value into separate variables. Here’s an example:

1
2
3
4
5
6
7
8
9
<?php
 
$array = array('a'=>'orange', 'b'=>'apple', 'c'=>'pear);
 
foreach($array as $key => $value) {
     echo $value;
}
 
?>

What we’ve done here is we’ve made a simple array, and used foreach to separate each array value into its key and value, and made these variables. The above will output just the values of every item in the array. That way we can manipulate individual parts of an array easily.

Functions

Functions are very handy, especially if you start to get into object orientated programming in php, and larger projects. A function has a basic layout as follows:

1
2
3
4
<?php
 
function functionname(parameter1, parameter2) {
}

you can call the function whatever you want (change functionname), and you can have as many parameters as you want. Parameters are just variables. You can define them in the function or on the fly. For instance, you could have something like this:

1
2
3
4
5
6
<?php
 
function yourname($name = "admin") {
     echo"hello, my name is $name";
}
?>

If you define the variable in the function (as I’ve done above), it means that that will be it’s default value. However, you don’t have to define the variable here, and later on in the script you can call the function and change the name. For example:

1
2
3
4
5
6
7
8
<?php
 
function yourname($name = "admin") {
     echo"hello, my name is $name";
}
 
yourname("Jonathan");
?>

As you can see above I called the function, and set my “$name” to Jonathan.

Include and Require

Sometimes you’ll have an external file you wish to include into another php file. To do this we use either include or require. The difference between include and require is include only produces a warning if the file is not found, whereas require will cause a fatal error, causing the script to stop. There is also include_once and require_once. These functions are exactly the same as include and require (respectively), the only difference being if the file is already included or required, it wont be again. Here’s an example of include, however require, require_once and include_once work in exactly the same way.

1
2
3
4
5
<?php
 
include"/link/to/file.php";
 
?>
Forms and PHP

You can use forms to get user data and then use that data in a php script. This isn’t that hard to do. First of all you’re going to need a form, though:

1
2
3
4
<form name="input" action="" method="get">
     <input type="text" name="item1" />
     <input type="submit" value="Submit it" />
</form>

Try entering some data into this form. You’ll notice the URL in your address bar changes, adding ?item1= with the value you entered onto it. Let’s get started with the php, shall we?

1
2
3
4
5
6
7
8
9
10
<form name="input" action="" method="get">
     <input type="text" name="item1" />
     <input type="submit" value="Submit it" />
</form>
<?php
 
if(isset($_GET['item1'])) {
 
}
?>

Okay, let me explain what I’ve done here. $_GET['item1'] will get the value for item1, as found in the address bar. If the method we were using was post, we would use $_POST['item1']. isset is just a function to check if the variable is set, as in, it isn’t NULL. So then after this it’s just a case of putting the value into a variable.

1
2
3
4
5
6
7
8
9
10
<form name="input" action="" method="get">
     <input type="text" name="item1" />
     <input type="submit" value="Submit it" />
</form>
<?php
 
if(isset($_GET['item1'])) {
     $variable = $_GET['item1'];
}
?>

Now we can manipulate this data using if and else statements as explained above in this tutorial. It’s also possible to enter this into a MySQL database, which brings us onto our next topic..

MySQL and PHP

If you have MySQL installed on your server, it’s a very useful tool to be using. To initiate a connection to a MySQL database we use two functions, as shown below:

1
2
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

There’s a 90% chance you won’t have to change “localhost”, but all the other settings you’ll have to find out for yourself. The “username” and “password” settings are just your mySQL username and password. This connects to your MySQL server. The next line, selects the database you wish to use. “or die(” just is what happens if the connection is a failure, and in this case I’ve set it to output a mysql error. Another useful function to know is mysql_query(). This allows you to run MySQL Queries, which you put inside the brackets (in speech marks). I’m not going to go into mysql queries, as that’s another tutorial, but I hope these tips will help you.

Final Notes

That about covers this tutorial. However, if you want me to write any other tutorials or anything, please contact me using the contact page and I’ll happily try to do it. This tutorial was just so you could get the basics of PHP down, and it is very basic. I’d suggest playing around with it a bit, and maybe combining some of the functions and statements to make your own little php scripts. Don’t forget to check out PHP.net to get a full list of functions and features.


Share This

 

 
 

Author: Johnny




Johnny is the owner of Webtint and usually the sole contributer to the site (apart from the ocassional guest post).


Comments



Marcus Lind July 26, 2009 at 4:17 pm

Nice tutorial, I’m thinking about creating a PHP tutorial for beginners in my blog so I’m looking what others have covered and getting some ideas how to structure it.

You covered all the basics and even some of the more in depth things as functions. Good job!


W. Luis Martinz July 29, 2009 at 4:02 am

Great Tut Mate!! xD thx and keep working on tuts like this


    Jonathan July 29, 2009 at 5:49 pm

    Oh well gosh, thank you =] You might wanna check out our latest PHP tutorial if you liked this one.


Murray July 31, 2009 at 6:38 pm

Nice one.

I already understood most of what you covered, but it helped reinforce it.

I’m getting pretty proficient working in PS and HTML/CSS, but lately I’ve been getting my hands into PHP, which has been quite a bit of fun.

The MySQL queries should be a great tut, that’s what I’m really looking out for.


knox deltree August 3, 2009 at 6:04 am

Niceeeee!!! Pls when is the second lesson coming up?


    Jonathan August 3, 2009 at 4:12 pm

    hey, I’ll be writing more php tutorials in the future. So you might want to subscribe or follow us on twitter, to get quick updates about when they will be ready.





Leave us a Comment



Put your name here:

Your email goes here:

Got a Website? Put it here (optional):

And finally, your comment:




Sponsors