PHP basics tutorial

Ranked #1,589 in Internet, #92,988 overall

Get your hands on the basics of PHP within a few minutes!

In this tutorial the basics of PHP will be explained with simple and easy-to-understand example codes.

This tutorial was made for people who are totally new to programming in general ( might already know HTML, not necessarily ) and want to start off learning PHP right away with a basics tutorial that's easy to grasp. There's no requirements for this tutorial as for pre-knowledge at all. It's for the total newcomers to PHP programming and will discover the pure basics of programming in PHP.

Talked enough, let's program! ;)

What is PHP?

What is it, how and wherefor can I use it?

PHP ( Php Hypertext Preprocessor ) is a web programming language that can be used to create your own website systems. It can be combined with many other scripting languages such as HTML and CSS which are used for the layout of your webpage ( graphical content ). PHP is used to create the actual system for your website and is not too hard to learn. To run PHP scripts ( execute them inside of a webpage ) a compiler is needed or a webhost that has it built in. There are many free webhosts out there on the web that can run PHP codes ( most likely any of them can, nowadays ). However, it's also possible to run/test your PHP codes from your personal computer. All that's needed to do so is Apache. There's diverse software for this and I personally use XAMPP ( also have used WAMP ) which is an easy to use program that makes you able to easily run your PHP codes inside of your web browser. To start programming in PHP from your personal computer, do as following:

1. Download XAMPP.

2. Install it.

3. Run XAMPP (\installation\path\xampp-control.exe (for ex.: C:\xampp\xampp-control.exe)).

4. Start Apache (under Modules).

And you're ready to go! You can now run any PHP file that's placed inside of the directory installation\path\htdocs (for ex.: C:\xampp\htdocs).

Note: As mentioned above, the alternative to an apache server on your personal computer would be to find a free webhosting that runs PHP codes ( there are plenty out there ), for example 000webhost.com.

Time to program!

Creating your first very small PHP script!

Now it's time to actually write a PHP script!

We'll start with creating a "Hello World!" webpage ( original, no? ).

First create the PHP file, call it: test.php and put it inside the htdocs directory of your XAMPP installation folder ( e.g. C:\xampp\htdocs ). Do make sure the .php inside of the filename is used as extension for the file, and not as name ( e.g. not test.php.txt but test.php ). Now open it with notepad and write the following inside of the file ( will explain in a second ):

<?php
echo "Hello World!";
?>

Save it. Now open your web browser ( make sure XAMPP-control.exe is running and Apache is started ) and go to http://localhost/test.php. If you done it correctly, you will now see the following text appear on the screen:

Hello World!

Ain't it amazing? ... ok it may not be that amazing, but it's a start right?

So, you may already have realized that http://localhost refers to the htdocs directory of your XAMPP installation folder (e.g. C:\xampp\htdocs) and so we can go to http://localhost/path/to/file to access any PHP files we made inside of this directory ( including the test.php we just made ) and the web browser will execute the PHP script. Now let's have a look inside of the PHP script we just made. It started with some weird tag <?php and ended with ?>. These (so called) tags indicate the start and end of a PHP script. This way the browser knows that what we're programming in is PHP ( so it knows how to convert/compile the code ). These tags are required for a PHP code to work. Always start a PHP code with . Also note that inbetween of these tags you may only write PHP codes ( no normal text or other codes than PHP ).

Then there's the following line:

echo "Hello World!";

You might already have guessed that this is the part that writes the text "Hello World!" on the webpage. This is exactly what the echo function does. It's an PHP built-in function that is used to display text on a webpage. The only parameter the function needs is the text to display ( in this case "Hello World"). In functions in PHP, this parameter ( the thing the function needs to do its job ) is put behind the function name ( in this case echo ) and if it's text, it's put between quotes. However, for normal functions these parameter(s) should be put between brackets. For the built-in echo function this is not necessary, but you may also write:

echo("Hello World!");

for if you like. Another function that does exactly the same is the print function, however it tends to be slower so I personally prefer the echo function above the print function.

print("Hello World!");

Also note that each sentence in PHP ends with a ; symbol. This is strictly required for each sentence to end with, otherwise the webpage will throw out a parse error. So take good note of that if you don't want to end up in loads of parse errors!

That's it, your first very simple webpage in PHP displaying text, has been created successfully! Next is: creating a PHP code using variables. These are a vital part of programming in PHP and you'll need to use them a lot if you're planning on creating PHP systems ( which I assume you are ).

Using variables in PHP

What are variables and how to use them in my PHP script?

Variables in PHP are used massively. A variable consits of a name and a value. It is used to save data (text/numbers/etc.) into so that it can be re-used easily. For example: you have a very long text but don't want to write it over and over when re-using it later in your script again ( besides it takes a lot more code and resources to rewrite a long text unnecessarily ). Then you might want to just give that long text a name ( like: putting it inside of a box with a name on it ) so that it can be used later again just by calling the name ( like: opening the box again ). And that's exactly where variables can be used for.

So let's see how a variable is created in PHP. As mentioned above it consists of a name and a value, these are binded through a = symbol and the name is preceded by a $ to indicate that it's a variable:

$variable_name = variable_value;

The variable name may not consist of spaces or any other special characters other than an undercore ( for the rest: alphabetical characters and numbers ). The value can be anything: a string ( text ), a number, a boolean (true or false value), anything. Do note that strings should be put between quotes, and numbers should not:

$string = "some text";
$number = 10;

A variable's value can be reset at any time just the same way as it was set. To use a variable, simply call it's name preceded by a $ symbol ( just like it's used above ). For example, to display the value of a variable on the screen:

echo $variable_name;

We can use the echo value which we learnt to display text on a webpage. We can also make calculations with variables, for example try and run this code:

<?php
$num = 1;
echo "num = ".$num." .";

$num = $num+3;
echo "num = ".$num." .";

$num = ($num+1)*2;
echo "num = ".$num." .";
?>

which will output:

num = 1. num=4. num=10.

The normal mathematics rules count here. You may notice that we put the text between quotes and then seperated the variable from the text by ending the quotes and putting a dot. This is necessary because variables should ( usually ) not be put inside of quotes and should therefore be seperated from the quotes. This is done by ending the quotes and putting a dot before the variable. To continue the text after the variable, we put a dot behind the variable and reopen the quotes. It's also possible ( when using double quotes and no array deminsial variables ) to seperate the variable from the text by using accolades, like this:

echo "this is the value of a variable: {$variable_name} -cool.";

Also, the calculations we done can be written faster ( some of them ). The following calculations:

$num = $num+3;
$num = $num*2;

can be written also like this:

$num += 3;
$num *= 2;

So thats just a way to write simple calculations faster. It's even possible to add 1 to the $num variable by just typing $num++;.

Note: When you want to print a variable literally ( instead of the value of the variable ), then the dollar sign should be escaped by putting a backslash before the sign. This way the sign is treated as plain text, and not as a sign that indicates the start of a variable.

Using loops in PHP

What are loops and what can they be used for?

Loops can be very useful and they occur in many programming languages. They're used to repeat a certain code a certain amount of times or when a certain condition is true. Thus a loop consists of a condition and an executable code. There are a few basic loops that will be explained here. The first loop is the if loop, which is used to execute a certain code only when a condition is true.

if( condition ) {
executable code
}

As you can see there's a strict structure in the loop. It starts with the name of the loop ( in this case: if ) followed by brackets containing the condition of the loop which should be true in order for the code between accolades to be executed. So for example: we could have a variable containing a secret number and a variable containing the user input ( assuming we put this in a variable beforehand ). Now we would like to check whether the user input is equal to the secret number ( in order words: whether the user guessed the number correctly ). This can now be done easily with use of the if loop:

<?php
$secret_number = 79;
$guessed_number = 62;

if($guessed_number == $secret_number) {
echo "You guessed the number correctly!";
}else{
echo "I'm sorry but {$guessed_number} is not the secret number.";
}
?>

which outputs in this case:

I'm sorry but 62 is not the secret number.

As you can see we used == to check whether $guessed_number is equal to $secret_number. That's an important difference with using = which actually sets a variable ( instead of comparing a variable ).

The accolades can as well be left out but only for single line executable codes!

The while, do-while and for loop
Another much used loop in PHP is the while loop. This loop can be used to repeatively execute a code as long as a condition is true.

while( condition ) {
executable code
}

A variant to the while loop is the do-while loop, which executes the executable code atleast once( independent of the condition ).

do {
executable code
} while ( condition );

Well, back to the while loop. If we want to execute a code 10 times ( for showing the numbers 1 through 10 for example ) it would look like this:

<?php
$i = 1;
while($i <= 10) {
echo " {$i} ";
$i++;
}
?>

which will output:

1 2 3 4 5 6 7 8 9 10

We can also use the for loop to do this. Which is more restricted to execute a certain code for a given amount of times and is structured like this:

for( set init value; condition; action ) {
executable code
}

So for example for doing the same as with the while loop (counting to 10):

for($i=1;$i<=10;$i++) {
echo " {$i} ";
}

We first set $i equal to 1 (begin value) and set the condition that $i should not be greater than 10, and as action that $i should be increased by 1 each time the executable code is executed ( which displays $i ). Which results in counting through the numbers 1 to 10 and displaying them.

Do note the difference between the while and for loop: the for loop needs a specific amount of times to repeat to be set and the while loop does not and can therefore be used more diverse.

Comparison & Logical Operators

Operators to use inside conditions of your loops.

We now know how to create loops and what to use them for. But within a condition of a loop: how do we make certain comparisons or even combine multiple comparisons? That's what's up next. There are multiple operators that can be used to accomplish comparisons. Here's a list of them with their meanings.

Comparison Operators
These are used to actually make comparisons.

Operator

Meaning


==

equal to


!= or <>

not equal to


<=

smaller or equal to


>=

greater or equal to




Logical Operators
These are used to combine comparisons ( for ex.: comparison 1 needs to be true AND comparison 2 should not be true ).

Operator

Meaning


AND or &&

and


OR or ||

or





Note: Another useful operator can be the ! sign, which means litterally NOT. It can invert a comparison, for example:

if(!($foo == $bar AND $x > $y))

which is equal to the comparison:

if($foo != $bar AND $x <= $y)

You might also like ...

Loading

Next PHP Tutorial

Loading poll. Please Wait...

Comments & Questions

Got any questions about the tutorial or just want to comment? This is the place to do so.

  • Ram Oct 2, 2011 @ 1:19 am | delete
    hi! I am new to php, your lens help me lot and thanks

    Regards,
    ram
  • dogface Aug 19, 2011 @ 12:45 pm | delete
    Wonderful lens! Oh, and I already knew everything by the way. ;-)
  • edzsquid Aug 4, 2011 @ 4:26 am | delete
    Great lens! I will wait for your next lens!
  • corrytohsan Jul 10, 2011 @ 9:37 am | delete
    Thanks it's help me a lot.
  • RecnepsDaGreat Jun 21, 2011 @ 7:48 pm | delete
    Great Lens! I haven't ever gotten into PHP but I have done a little programming. I think your bio is hilarious. It's so true
  • Load More

Related Products (Amazon)

Loading

Related Products (eBay)

Loading

by

webcodez

"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."

webcodez
GameHeroes
more »

Feeling creative? Create a Lens!