PHP For Beginners: The Ultimate 1h Tutorial

Learn to code in PHP in an hour with this PHP for beginners tutorial.

Share This Post

While PHP has been around for a while, there are always good modern reasons to learn it. In fact, PHP is one of the most user-friendly programming languages. In other words, in case you are new to programming, you can get up to speed really quickly. With this PHP for beginners tutorial, we will show all you need to make a functioning dynamic website. And you can have it up and running in about 1 hour.

What is PHP?

PHP is a programming language for making websites. It has been designed specifically for that, and that’s what it does best. PHP is open-source and widely compatible: you can run it on Windows, Linux, and macOS. It is also very light, which means you don’t have to have a powerful server to run it.

If you want to learn more about PHP, why you should use it, and even why some people hate it, read here. In this tutorial, we focus on the practice, not on the theory behind it!

Before you start… Install PHP!

Most computers do not understand PHP by default. After all, it is a server language, so why should they bother? However, we want our computer to act as a web server, so it needs to understand it. No problem, we simply need to install PHP on it. If you are on Windows, we have a perfect tutorial that shows you that.

Install PHP (or XAMPP on Windows) first. Otherwise, you won’t be able to run anything of this tutorial.

PHP Beginners Tutorial

How does it work

Before we start writing fancy PHP code, we should understand what happens on a web server. A web server is a device sitting on the Internet waiting to serve requests. A client, like your PC, makes some requests to the server, that will eventually reply. For example, when you are surfing on this website, your PC will ask ictshore.com’s servers “hey, get me this page”. If you later navigate to a different page, it will ask again “okay, now I need this other page”. Of course, the server will reply with the pages.

Before we dive into this PHP for Beginners Ultimate tutorial, we need to understand some basic PHP.

The protocol to exchange requests and responses is HTTP, or HTTPS (the secure version, which is equivalent for the purpose of this tutorial). However, the client doesn’t simply ask. Sometimes, it also provides the server with some information. That’s the case when you submit a form: adding a comment to a blog post, making a purchase on Amazon, and so on.

Of course, this is a oversemplification of the process. Still, it gives you all the knowledge you need to make a PHP website.

The role of PHP

Now it is time to dive into our PHP for beginners tutorial. When the client makes some requests to the server, the server has to process them and give the proper reply. PHP is the language to do that (of course, there are lots of alternatives). Based on the request, the server will trigger a different PHP script, that will have to create or get the response.

If you call example.org/index.php, your request will be processed by the script located in index.php file. There are also nice ways to make URLs better looking, without having to show to the user the PHP file name, but that’s out of scope for today. It is not something to cover in a PHP for beginners tutorial, as it is not even PHP that does that.

Our first PHP Script

If you followed our tutorial on installing XAMPP, you will have your web server folder at C:\xampp\htdocs. That’s the folder that should contain your PHP scripts. Start Apache from your control panel, and you should be able to navigate to that folder on the localhost website. For example, if you go to http://localhost/index.php, you will launch the script at C:\xampp\htdocs\index.php.

Obviously, you need to have that PHP file here. If you don’t, you won’t launch any script but get an error instead. XAMPP puts some default files inside the C:\xampp\htdocs folder, that we will call document root from now on. You can remove them, it won’t cause any issue.

Once you removed all the files, create an index.php file. How can you do that? Simply open Notepad and save a file named index.php here. But pay attention. You need to change the extension from .txt to All files when saving, otherwise, you will get something like index.php.txt, that won’t work!

In this PHP for beginners tuorial, we will see how to create a PHP file with your simple notepad that comes preinstalled in Windowa
It is important to save your PHP file as all files if you are using notepad to edit it.

Hello World

All your PHP files should start with <?php on the first line, and end with ?> on your last line. This is what tells your web server that there are some PHP instructions in it. With echo, you can write a message on the response that will be sent to the client. That response, in turn, will appear as a web page. Here is your example.

<?php
   echo "Hello, world!";
?>

Here note two things:

  • We enclosed Hello, world! in quotes. This tells PHP that we actually mean Hello, world! and not some strange PHP instruction to parse (unlike echo, which PHP will understand because it is not quoted).
  • Each PHP instruction must end with a semicolon

Now, if you navigate to your http://localhost/index.php, you will get your Hello, world! message. It will probably appear in an ugly font, as we haven’t provided any style. However, providing style is not the job of PHP, and we won’t cover it here.

Variables

PHP allows you to create dynamic pages. That’s the purpose of our PHP for beginners tutorial, after all. The pivot elements here are the variables. You can imagine them as placeholders for a value that may change. Think of them as boxes, you can put every time something different in the box. Later in the code, whenever you use the box, PHP will use what is inside that box at that moment. And, of course, you can change the value inside the box multiple times during your code.

To define a variable, you have to give it a name that starts with $ and may contain letters, numbers (but the first character cannot be a number) or underscores. Then, you write an equal sign and then write the value you want your variable to start with. In other words, you provide the initial content of the box. Later, you can reference your variable by simply using the name.

<?php
   $name = "Joe";
   echo "Hello, " . $name;
?>

This way, we print Hello, Joe. Note that the dot on the echo line means join these two pieces of text. Variables can also be number, that support all basic math operations. Take a look:

<?php
   $number = 10;
   echo "In the first step we have " . $number . "<br>" ;
   $number = $number + 1;
   echo "Now the number became " . $number . "<br>";
   $number = $number * 2;
   echo "And finally we got " . $number . "<br>";
?>

Note that <br/> at the end of each echo line is to ensure a line return when the page renders. The message will be this:

In the first step we have 10
Now the number became 11
And finally we got 22

Variable types

A variable is a box, and a box can contain several things. Specifically, it can contain things of several types. PHP provides you with some default simple types. You also have complex types, but they are nothing more than a combination of simple types. Here is what you get by default:

  • A string is a piece of text. You define it by writing the value between double or single quotes (for example $variable = "my text")
  • An integer (or simply int) is an integer number, and you define by simply specifying the numeric value ($variable = 5).
  • Instead, a floating-point number (known as float) is a decimal number, and you define it by specifying some decimals ($variable = 4.11). Note that if you define a variable with value of 4 it will be an integer, if the value is 4.0 it will be a float. For basic stuff, it does not matter: PHP can take care of conversions automatically.
  • Finally, we have the boolean (or bool), which represents the status of being true or false. It is important to represent conditions. You define with the special keywords true and false, without quotes ($variable = true or $variable = false).

You also have the possibility to set your variable box as empty, with no value. Simply set it to the special keyword null ($variable = null).

Conditional programming

You may want to do different things based on some variables. For example, you may want to show a different page to logged user compared to the page you have for guests. You can do that with the if and else statements. The syntax is simple, you need to write a condition between the brackets, and then all the instructions you want between curly brackets. For example:

<?php
   $number = 4,
   if ($number < 10) {
      echo "Okay the number is less than 10";
      echo "In fact, the number is " . $number;
   } else {
      echo "Sorry, but you got above the limits!";
   }
?>

Try to change the value if $number to 11, and see that the page will render the code block of the else statement. You don’t need to put curly brackets on the same line of the condition, you can go to a new line also after the condition and also before the else if you want.

Remember, the code block of the if will be executed if the condition is true, the code block of the else if it is false. And, of course, the else statement is optional.

Comparing things

If you want to compare two things in a condition, like we did, you need to know the way to do it. Here are the symbols you can use, between two given values a and b.

ExpressionDescription
$a < $bIt is true if $a is less than $b
$a > $bIt is true if $a is greater than $b
$a <= $bIt is true if $a is less than $b or equal to $b
$a >= $bIt is true if $a is equal or greater than $b
$a == $bIt is true if $a is equal to $b
$a != $bIt is true if $a is different than $b
Operators

Multiple conditions at once

Imagine you want to check if a value is between two other values. Something like 0 < $a < 10. You cannot write exactly that, because conditions normally compare only two values. How can you do that? You may create one if with the first condition, and another inside it with another condition. The code can start to get really messy, but we have a better option!

You can write individual conditions between brackets and then join them with two operators:

  • && will result in true in case both conditions are true at the same time
  • || will result in true in case at least one of the two conditions is true, even if the other isn’t

So, we can rephrase our initial conditions into something like that:

<?php
   $n = 4;
   if ( (0 <  $n) && ($n < 10) ) {
      echo $number . " is between 0 and 10!";
   }
?>

You can also negate a condition by adding ! before it. This way, the result will evaluate to false if the condition was true, and vice versa.

While Loop

With loops, you can repeat an instruction multiple times. It may be useful in case you want to render a list or something like that. This is possible with the while statement. This special statement evaluates a condition, and if it is true it runs a code block. Then, it evaluates the condition again and repeats the process. In your code block, you may want to modify the value of the variable inside the condition, so that the condition will eventually become false. When the condition is false, PHP will exit the loop, and continue normal execution.

Take a look at the following example.

<?php
   $n = 0;
   while ($n < 5) {
      echo 'Our variable $n is worth ' . $n . ' at this time <br>';
      $n = $n + 1;
   }
   echo 'Finished! Now $n is ' . $n;
?>

Note that we used a single quote because we written $n in our text. If we used double quotes, PHP would have recognized the variable name and replaced it with its value. The result is the following.

Our variable $n is worth 0 at this time
Our variable $n is worth 1 at this time
Our variable $n is worth 2 at this time
Our variable $n is worth 3 at this time
Our variable $n is worth 4 at this time
Finished! Now $n is 5

For loop

If you want to repeat an instruction a given number of times, just like we did, the for loop may be your best choice. The syntax is simple: for (a; b; c) { ... }. Instead of a, you need to write an instruction to execute before starting the loop. Then, instead of b, you need to insert the condition to check every time you run an iteration of the loop. Finally, instead of c, you need to write an instruction to do after the check.

This typically translates to: you set a variable to zero in the first space, then check for its value in the second, and increment it in the third. So, to replicate the same output we had above with a for loop, we can write.

<?php
   for ($n = 0; $n < 5; $n++) {
      echo 'Our variable $n is worth ' . $n . ' at this time <br>';
   }
?>

Note two things. First, $n++ is a shortcut for $n = $n + 1. Then, the $n variable exists only within the loop, and it won’t be available outside.

Arrays

An array is a complex type of variable available by default in PHP. Unlike a normal variable that contains one value, an array can contain many values. In fact, an array is a list of items. When you want to access the item in the array, you need to ask PHP “Okay, give me the first element”, or second element, and so on.

You do that by mentioning the item position. Note that the first position in PHP, as in many programming languages, is position zero.

To define an array, use $variable = []. Now, your variable will be an empty array. To add items, you can use $variable[0] = "The first item". Now you can start to see how you can use a for loop:

<?php
   $variable = [];
   $variable[0] = 'The first item';
   $variable[1] = 'Second item';
   $variable[2] = 'Third and last!';

   for($i = 0; $i < count($variable); $i++) {
      echo $i . ': ' . $variable[$i] . '<br>';
   }
?>

Note the count function that gives you the number of elements an array has. This will result in the following output:

0: The first item
1: Second item
3: Third and last!

You can also pre-fill your array when you initialize it. In that case, simply add its value between the brackets, separated by commas. PHP will put them in order, starting from position 0. Try to rewrite the previous code with the following initialization.

$variable = ['The first item!', 'Second item', 'Third and last!'];

Associative arrays in PHP

The position of the item in the array is known as the key. We saw integer keys, and they are cool for a sequence of things. However, PHP supports also strings as keys. You want to use them if you want to describe a complex thing, instead of a list of simple things. For example, imagine you have products in your stock. For each, you may want to know the name, the code, the quantity available, and the price. You can conveniently store each product in an associative array.

<?php
   $product = [];
   $product['name'] = 'Apple';
   $product['code'] = 'apple-01';
   $product[qty'] = 10;
   $product['price'] = 2.30;
?>

Note that we have in the same array strings, integers, and floats. This is completely okay with PHP. You can also pre-initialize the value with the special syntax key => value, like so:

 <?php
   $product' => [
      'name' => 'Apple',
      'code' => 'apple-01',
      'qty' => 10,
      'price' => 2.30
   ];
?>

Okay, but now our for loop won’t work anymore. What do we do?

Foreach Loop

The foreach loop is designed to scan through the items in an array, both traditional arrays and associative arrays. The syntax wants to know the array name, the name of the variable to store the key in, and the variable to store the actual value in. You need to use new variables, that are specific to the loop and that were not using before (unless in another foreach). A common approach is to use $key and $value as variable names.

 <?php
   $product' => [
      'name' => 'Apple',
      'code' => 'apple-01',
      'qty' => 10,
      'price' => 2.30
   ];

   foreach ($product as $key => $value) {
      echo $key . ' = ' . $value . '<br>';
   }
?>

And this results in the following output.

name=Apple
code=apple-01
qty=10
price=2.30

Processing user input

The form

Okay, having variables and conditional programming is good, but useless unless the variables will actually change. The most common thing to do is to have your code do something different based on the user input. Our PHP for beginners tutorial would be useless without it.

First thing, you need to allow the user to give you the input. This is possible with an HTML form. A form is a set of variables you ask the user to fill. Each variable is defined in an input tag, and all are enclosed inside the form tag.

Here is the code to make a form that asks three values. Note the name attribute, it will be the one we will use later to reference those variables.

echo '<form action="/index.php" method="POST">';
echo '   <input type="text" name="a" />';
echo '   <input type="text" name="operator" />';
echo '   <input type="text" name="b" />';
echo '   <button type="submit">Calculate</button>';
echo '</form>';

In the first line, we define that the form will have to send the data to the index.php page with the POST HTTP method. That method is used when the user submits data for processing.

Processing the data

Now, we need to integrate the form into our code. We want to check if the user provides the data and if so show the result of the calculation. Then, we always want to show the form to allow the user to enter new data. Here is how we can do it.

When the user provides data, PHP will put them in the special $_REQUEST array. Here, we can access them with the name we gave to the input tag in the form.

<?php
   isset($_REQUEST['a'])) {
      if ($_REQUEST['operator'] == '+') {
         $result = $_REQUEST['a'] + $REQUEST['b'];
      } else if ($_REQUEST['operator'] == '-') {
         $result = $_REQUEST['a'] - $REQUEST['b'];
      } else if ($_REQUEST['operator'] == '*') {
         $result = $_REQUEST['a'] * $REQUEST['b'];
      } else if ($_REQUEST['operator'] == '/') {
         $result = $_REQUEST['a'] / $REQUEST['b'];
      }
    
    if ($result !== null) {
       echo 'The result is ' . $result . '<br>';
    }
   }
   
   echo '<form action="/index.php" method="POST">';
   echo '   <input type="text" name="a" />';
   echo '   <input type="text" name="operator" />';
   echo '   <input type="text" name="b" />';
   echo '   <button type="submit">Calculate</button>';
   echo '</form>';
?>

First, we check the key a in the $_REQUEST array is set. If so, we start to check the operator, and based on that we assign a value to the result. Note that the else if construct allows you to chain a if to another if, with the second being executed only if the previous was false, and so on.

Then, we check that the result is not null. We are using !== instead of !=, because != would treat 0 and null in the same way, as it does not consider the type of the variable. If the result is not null, we show it to the user.

Note that if the user does not insert valid numbers or operators, we get some ugly errors. That’s outside the scope of our article.

Functions

Functions are a set of instructions you define and later call for execution. They make your code reusable because you define a set of things you want to do in one place only. Then, whenever you want to do those things, you simply use the function name. You define them with the function keyword.

<?php
   function sayHello() {
      echo 'Hello! <br>';
   }
   
   for ($i = 0; $i < 10; $i++) {
      sayHello();
   }
?>

This will print the hello message 10 times. You need to define the function before you use it. If we put the for before the function, it won’t work.

Functions can also accept parameters, or variables you want to make available inside the function, like so:

<?php
   function sayHello($name, $n) {
      echo 'Hello to ' . $name . ' for the ' . $n . ' time! <br>';
   }
   
   for ($i = 0; $i < 10; $i++) {
      sayHello('John', $i);
   }
?>

You can pass as parameter a static value (like we do for the name), or another variable. In the latter, the value of the variable will be copied inside the function. If you modify the value inside the function, it will not affect the outside variable. Note that this is a little bit more tricky than that for complex types, but we are going outside the scope of our PHP for beginners tutorial.

Finally, a function can return a value. Returning a value means making it available outside the function. In other words, you make the functions do some calculations and get the results. Like so:

<?php
   function sayHello($name, $n) {
      return 'Hello to ' . $name . ' for the ' . $n . ' time! <br>';
   }
   
   for ($i = 0; $i < 10; $i++) {
      $message = sayHello('John', $i);
      echo $message;
   }
?>

Wrapping it up

So much stuff in this PHP for beginners tutorial. However, everything you see here is oversimplified and it is just a way to start. Let’s be honest, you are probably going to write some ugly code with what you learned here, we are still far away from professional programming.

Still, if you can grasp the logic of programming, form conditions to loops or variables, you are set of a great career in IT. What you learned here are great tools that allow you to experiment. Try some different things, get some errors, and just google to fix them. Eventually, you will have a solid understanding of the concepts underpinning programming.

What do you think of PHP? Are you able to play with it after this tutorial? Let me know your opinions in the comments.

Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.
Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded ICTShore.com with the same principle: I share what I learn so that you get value from it faster than I did.

Alessandro Maggio

2019-06-20T16:30:35+00:00

Unspecified

Dev

Unspecified