PHP BEGINNERS GUIDE

Published Jul 09, 2017
PHP BEGINNERS GUIDE

Contents

  1. Introduction
  2. Getting Started
  3. Basic Syntax
  4. Variables
  5. Operators
  6. Arrays
  7. Control Structures
  8. Functions
  9. Pre-defined Variables
  10. Expanding

Introduction

What's PHP?
PHP: Hypertext Preprocessor (PHP) is a free, open source, scripting language that is made primarily for the creation of dynamic websites. It is compatible with almost all modern servers and PHP scripts are always executed on the server. I would suggest a simple understanding of HTML. If you want a more in depth look into CSS and other aspects of site creation (which I recommend you do before diving head first into PHP) take a visit to the w3schools HTML tutorial. This can be accessed W3school. I will not be covering any HTML elements within this tutorial.

What can it do?
PHP has a huge collection of uses such as:

  • Database management
  • Generating dynamic content on a page
  • Handling data from forms
  • Controlling and limiting site access to users
  • Data encryption
    So much more!

The list of uses for PHP goes on and on. Because of this, it is the backbone behind some very big websites and it powers the world's most popular CMS (content management system) WordPress.

Getting Started

Installing
To get started with learning PHP you first need to install or buy a web server to host the files on. For this tutorial we will be using XAMPP, this is a free tool which allows for an easy set up of a local web server. Download and install XAMPP from http://www.xampp.org/. Once you have XAMPP open up the control panel and click on start for Apache and MySQL, these are the only 2 modules we will be needing.

Other than this you will also need a text editor for creating the PHP files. The two most common editors are Sublime Text and Notepad++. I personally use Sublime Text however both are good choice and you can get Sublime Text from here and Notepad++ from here.

Now that's all done we should probably check if your XAMPP is working. To do this we will make a very simple script just to check.

<?php
     echo "Welcome to PHP";
?>

Create a new .php file using the editor you installed and drop it into the XAMPP htdocs directory and call it "hello.php". If you are using windows and used the default XAMPP install directory, your htdocs folder will probably be at C:\xampp\htdocs\ if you can't find it. Once you've done all this go to your browser and type in http://localhost/hello.php and if you have followed all these steps you should be greeted with a page saying "Welcome to PHP".

Congratulations! You're now one step closer to becoming a PHP pro!
Before continuing I'd suggest reading this. It is the PSR-2: Coding Style Guide and will stop you from getting into bad habits while creating scripts. Making functional code is for the users benefit, you should make beautiful code for not just other developers who see your work, but also for yourself.

Basic Syntax

PHP Tags
All scripts start and end with these tags:

<?php
     //Code goes here.
?>

The PHP tags can be placed anywhere in your document.

Here is an example where I have used a function called echo to print out "Hey" on to a web page.

<?php
     echo "Hey";
?>

As you can clearly see, the PHP tags are indicating to my computer where my PHP code begins and vise-versa when I use closing PHP tags. They can also be opened and closed multiple times throughout the file.

Echo
PHP has a built in function called "echo" which has the job of outputting text. It would be a mistake to call it a function as it is actually a language construct, this means it does not require parentheses. As with all PHP statements, the echo construct must always end with a semi-colon ";" so it is clear where each line ends. We've already had two examples in this tutorial where we have used echo so go back and have a look at how they were written. All the outputs of echo are in plain HTML meaning you can use HTML tags within it.

<?php
     echo "<strong>This will output strong text!</strong>";
?>

Comments
A comment is a line or section of code that is not executed as part of the program. Comments serve the role of communicating to others and your self how certain bits of your code work or what they are used for. The first kind of comment is a single line comment. To begin one of these you simply do // and anything on that line after the slashes will not be executed. The other option is a multi-line comment, these are started with /* and end with a */. Anything between this two will not be treated as code. Let's have some examples of comments so you can understand exactly how they look in practice.

<?php
     //This is a single line comment. It only comments this line
     echo "Hello world";
     /*
     This is a multi-line comment. It comments anything between the constructs.
     */
?>

That's all the most basic syntax out of the way. These were beginner constructs that you will need to know but don't fall into any other categories of the tutorial. It is also important to note that these constructs can't be changed. However, now you should be able to write a basic PHP script.

Variables

Regular Variables
Variables are containers which we use for storing information. PHP variables work a bit differently to other languages so I suggest you pay close attention here. A variable starts with a dollar sign ($) which is then followed by the name of the variable. That is then followed by a = sign and the value is entered after that. After the value you need a semi-colon as usual. Let's have an example.

<?php
     $var_name = 10;
?>

There are some important things you must remember when setting a variable name:

  • The name of a variable must start with a letter or an underscore.
  • Variable names are case sensitive (so $swag would not be the same as $SWAG).
  • A variable name cannot start with a number.
  • A variable name can contain only letters, numbers and underscores.

When defining a variable you do not have to tell PHP the data type. This is where it is a bit different to other languages and shares more in common with something like python as PHP looks at what you set the variable too and gives it a datatype based on that. Because of this, you also never need to declare a variable, it is created the moment you assign a value to it.

You can also use variables in other functions or constructs instead of directly typing in data. This comes in handy when you will be using a value more than once and don't want to have to retype it and/or when the value of it will be changing often. For example:

<?php
     $name = "Ciaran";
     //Since I put in the quotation marks PHP knows that is a string.
     echo $name;
     //Now the echo construct goes and looks for variable $name and outputs it.
?>

Constants
Now I did make a rant thread (disguised as a tutorial) on constants a while ago and I do think they aren't used enough by beginners these days. But you don't care about that. A constant is similar to a variable except it is defined once then cannot be undefined or have its value changed. The same rules for making a constant variable name apply here.

To create a constant you use the define() function.

define(name, value, case-insensitive) 

Parameters:

  • name: Specifies the name of the constant.
  • value: Specifies the value of the constant.
  • case-insensitive: Should the constant name be case sensitive? This is defaulted to false.
<?php
   define("HELLO", "Hello there friend.");
   echo HELLO;

   //Outputs "Hello there friend."
?>

Example using case sensitive:

<?php
   define("HELLO", "Hello there friend.", true);
   echo hello;

   //Outputs "Hello there friend."
?>

You can also define constants by using the const variable. This works in exactly the same way but is always case-sensitive and is defined a little differently.

<?php
     const CONSTANT = value;
?>

Instead of using define, you simple remove the $ from in front of a variable and use the keyword const in front of the variable name.

Data Types
A data type is the type of information stored within a variable. PHP has 8 main data types listed here:

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

Let's start with an integer. These are whole numbers without decimals that; don't contain commas or blanks, must not have a decimal point and can be positive or negative.

<?php
     $inta = 11; //Positive integer
     $intb = -11; //Negative integer
?>

Next is a string where is a "string" of characters. It can be any text within a set of quotation marks (double or single). You can also join two strings together using a dot concatenation operator.

<?php
     $stringa = "Hello there buddy."; //You could also replace the " with '.
     $stringb = "Nice weather today.";

     echo $stringa . $stringb; //This will add b onto the end of a and output them.
?>

A float (floating point mumber) is a numeric variable like an integer except it includes a decimal.

<?php
     $a = 107.5;
?>

A boolean is a variable that can be represented in two possible states: TRUE or FALSE.

<?php
     $x = TRUE;
     $y = FALSE;
?>

The other variables are a bit advanced for now and will be covered later in the tutorial. It's good to remember that most variables can be combined with each other and we will go into more detail about this later.

Variable Scope
The scope of a variable is the part of the script your variable can be referenced or used. There are three types of scope: local, global and static. A variable declared outside of a function has a global scope but can only be used outside of a function. Variables declared inside of a function with have a local scope and can only be used inside of this function. We will go into parsing local variables into global later using the return function.

<?php
     $var1 = 50; //This sets a variable with global scope.
     function printNum() //Defining a function (will explain this more later)
     {
          $var1 = 49; //Sets this variable with a local scope.
          echo $var1; //Will output 49 as it checks for variables with a local scope.
     }
     printNum(); //Calling the function.
?>

Operators

Arithmetic
Arthimetic operators work with numeric values to perform common arthimetic operations.

  • Addition | $a + $b
  • Subtraction | $a - $b
  • Multiplication | $a * $b
  • Division | $a / $b
  • Modulus | $a % $b
  • Exponentiation | $a ** $b

Most of these are self explanatory apart from modulus which some of you may not be familiar with. In short, it is the remainder of the division between the first and second operand. For example:

<?php
     $a = 14;
     $b = 3;
     echo $a % $b; // Outputs 2     
?>

And if you are confused to what exponentiation is, it is simply what you get when you raise $a to the power $b. For example:

<?php
     $a = 3;
     $b = 2;
     echo $a ** $b; //Outputs 9
?>

You can also do increment's and decrements. These can either be: post increment's, pre increment's, post decrements or previous decrements. To use a post increment simple follow the variable with ++ or -- for a decrement.

<?php
     // Post increments.
     $a++; // equivalent to $a = $a + 1
     $a--; // equivalent to $a = $a - 1
?>

The difference with a post increment is that it returns the value before it changes the variable. Pre increments change the variable then change the value.

<?php
     $x = 5; $y = $x++;   //$x = 6 and $y = 5 
     $x = 5; $y = $++x;   //$x = 6 and $y = 6
?>

Assignment
Assignment operators work with numeric values to write values to variables.

<?php
     $x = 42;
     $x = $num1
?>

Assignment operators can also work with arithmetic operators.

<?php
     $x = 5;
     $x += 10; // You can replace the + with any other arithmetic operator.
     echo $x;
     // Outputs 15
?>

Comparison
Comparison operators allow you to compare two variables. They will return a boolean answer of TRUE or FALSE. They are usually used inside of control structures which we will explain more about later. As for now, here is a list of all the comparison operators:

  • Equal | ==
  • Identical | ===
  • Not Equal | !=
  • Not Equal | <>
  • Not Identical | !==
  • Greater Than | >
  • Greater Than or Equal To | >=
  • Less Than | <
  • Less Than or Equal To | <=

Logical
Logical operators are used to combine conditional statements. Bellow is a list of all of them:

  • And | and
  • Or | or
  • Xor | xor
  • And | &&
  • Or | ||
  • Not | !

Arrays

Numeric Arrays
An array is a special type of variable that is capable of storing multiple values. Numeric arrays give a numeric index to all of the values within the array. The first index of an array is always 0 and there are two ways to define them:

<?php
      $myfirstarray = array(
           item1 => "value1",
           item2 => "value2",
           item3 => "value3",
      )

      //OR

      $array = array("value1", "value2", "value3");
      // You can also assign the index manually like this. 
?>

We access an element by referencing its

<?php
      echo $dogs[1]; // Will echo Lola.
?>

Associative Arrays
Associative arrays are similar to numeric arrays. However, the values in the array are given named keys that you assign to them. There are two ways to create an associative arrays:

<?php
      $characters = array("Kenny"=>"9","Stan"=>"10","Cartman"=>"8");
      //or
      $characters['Kenny'] = "9";
      $characters['Stan'] = "10";
      $characters['Cartman'] = "8";
      // both give the same result
?>

To access the values of this kind of array, you use the named keys instead of the usual numeric value.

<?php
     echo $characters['Cartman'];
?>

Multi-Dimensional Arrays

A multi-dimensional array is an array that contains one or more arrays. The dimension indicates the amount of indices you would need to select an element within in. For a two dimensional array you would need two indices to access it and for a three dimensional one you would need 3 and so on. Arrays more than 3 layers deep are very difficult to handle so I would suggest staying away from them. The arrays inside of the multi-dimensional arrays can be either numeric or associative. Let's create a two dimensional array:

<?php
     $people = array(
          'friends'=>array('Hunt','Draig')
          'enemies'=>array('Josh','Silver')
          'family'=>array('Sinead','Declan')
     );
?>

This two dimensional array has 3 arrays and two indices. We can think of these as a row and columns. To access this array we need to specify both the indices.

<?php
     echo $people['friends'][0]; //Outputs Hunt.
     echo $people['family'][1]; //Outputs Declan.
?

Control Structures

If Else Statements

Conditional statements perform different things for different states. The if else statement runs a piece of code if a condition is true and other code if the statement is false. The if can also be done by its self, if the statement is not true then nothing will happen and the program will simply continue. Let's have a look at an example:

<?php
     if(condition){
          //run this if condition is true
     }else{
          //run this code if condition is false, you can also remove this else and just have the if.
     }
?>

Now let's look at an example using some actual code:

<?php
     $x = 2;
     $y = 4;
     if($x == $y){
          echo $x;
     }else{
          echo $y;
     }
?>

Notice in the condition area where we are asking php if $x is equal to $y we can use comparison operators that we looked at earlier. These can also be added to logical operators by separating two conditions with them by simply placing them in the middle.

Elseif Statements

You can use an elseif statement as a continuation of your already existing if statement. They specify a new condition to test and can be used as many times as needed. Here is the syntax for them:

<?php
     if(condition){
          //run this if condition is true
     }elseif(condition){
          //run this code if second condition is true
     }else{
          //run this code if condition is false
     }
?>

And once again here is a code example:

<?php
     $x = 2;
     $y = 4;
     $z = 3;
     if($x == $y){
          echo $x;
     elseif($x == $z){
          echo $z;
     }else{
          echo $y;
     }
?>

While Loop
A loop allows you to run the same snippet of code multiple times with relative ease. This can be amade extremely helpful tool however is where many beginners start to make logic errors. The first loop I will show you is the while loop, it is very similar to the if statement but instead if checking a condition once, it will continue to do if until the condition is false. The syntax is very simple:

<?php
     while(conditon){
          //so until the condition is false do this code
     }
?>

It's very important to remember that if the condition becomes false the code will loop forever. Make sure there is a way for the condition to exit.

Now let's have a look at an actual code example:

<?php
     $apple = 20;
     $pear = 10;
     while($apple > $pear){ //While apple is bigger than pear.
          echo $pear; // output pear
          $pear++; //add one to pear so eventually the condition becomes false and the loop exits 
     }
?>

There is also a similar loop named the "do while" loop. It is the same as a whlie loop but it checks for the condition after it runs the code, meaning the code inside will always run at least once. It's syntax is largely the same but has the while statement in a different position. Let's have a look at the syntax and a working code example.

<?php
     do{
          //code
     }while (condition);
?>
<?php
     $x = 0;
     do{
          $x++;
     }while ($x==5);
     echo $x;
?>

For/Foreach Loop

A for loop is used when you know how many times you will need to loop the code in advance. Within them you first need to initialise a loop counter, then you need a condition to be checked so the program knows when to exit the for loop. You also need an increment to change the counter variable every iteration of the loop.

     for(init; test; increment){
          //code
     }
?>

Let's have an example that shows numbers 0 to 5. We will do this by accessing our counter variable which can be accessed only from within the loop.

<?php
     for($a; $a > 6; $a++){
          echo $a;
     }
?>

You can also use a Foreach loop which instead of giving a direct amount of times to run the loop, you give an array. The Foreach loop will then run the loop for every element of the array.

<?php
     $numbers = array(1,2,3);
     foreach($numbers as $num => $value){
          echo $value;
     }
?>

As you can see, this will print out every element within the array. The as in the loop allows us to access the current value within the array that the loop is using. This is updated every iteration to the latest value.

Switch Statement

A switch statement allows for, what would be, a long list of elseif statement but in a more optimised and clean manner. You give the switch a variable and then make a case statement for each value you want to check for. You end each case with a break statement and you can also use default as something a lot like the else command. Let's have a look at a quick example of a switch statement.

<?php
     $animal = "Dog";
     switch($animal){
          case "Cat":
               echo "your animal is a cat";
               break; 
          case "Dog":
               echo "your animal is a dog";
               break;
           case "Fish":
               echo "your animal is a fish";
               break;
           default:
               echo "your animal doesnt exist";
     }
?>

Ternary Conditionals

Ternary conditionals can allow for more compact and easy to read code by letting you do simple if/else statements on the fly. They have a syntax like this:

<?php
     variable = condition ? trueValue : falseValue;
?>

Now let's see a working example.

<?php
$var = 7;
$var = $var < 10 ? 11 : 7;
?>

These are useful for doing a very quick if statement however if you need to go deeper than 2 levels and want to add an elseif or such to the statement then ternary operators may be aren't your best choice.

Include and Require
The include control structure allows you to insert a php file into the contents of another. These can be useful when a script (such as one connecting to a database) needs to be run a large amount of times. Copying out all the code would require a large amount of time and wasted space. With include you can simply run a single line to take care of something like connections. They have a syntax of:

<?php
     include 'filename.php';
?>

This can be extremely useful when creating a header or a footer for your page as well. Require has the same syntax (except replace include with require) but unlike include, if the server fails to find the script a fatal error will be returned. With include the server would ignore this and keep going however, it would still show an alert on the page.

Functions

User Defined

A function is a block of code that needs to be used multiple times throughout your code. They aren't executed upon loading of a script but instead when they are called upon. A user defined function starts with the term function followed by the name, brackets and curly brackets. The code for the function goes inside the curly brackets. To call upon the function you use the name followed by brackets.

<?php
     function helloworld() {
          //Code to run goes in here.
          echo "Hello world.";
     }

     helloworld(); //Runs the function.
?>

Function names must begin with a letter or an underscore but may contain special characters and numbers. They are not case sensitive.

Parameters

The brackets that come after the function name are used for parameters. They allow you to pass values through a function. When defining your function you must put the name that you wish to referace the variable by into the parentheses. When calling your function you use this space for what you wish the parsed value to be. Multiple parameters can be used and are separated by commas. Let's see an example where a function multiplies two numbers.

<?php
     function multiply($num1, $num2) {
          echo $num1 * $num2;
     }
      
     multiply(3,2);
     //Outputs 6.
?>

Return

A function can return a value using the return statement. The statement stops the function and send a value back to the calling code. Multiple values cannot be returned so if you wish to do this I would suggest storing the variables you wish to return anymore than 1 value. Let's use our parameters example and add a return statement.

<?php
      function multiply($num1, $num2) {
          $answer = $num1 * $num2;
          return $answer;
     }
      
     echo multiply(3,2); 
     //We can now use the function as if it were a variable.
?>

Predefined Variables

Explanation
PHP comes with a wide collection of built in variables that allow you to do various things. These include things such as PHP Forms, GET, POST, $_COOKIE and a variety more. I feel these are a more intermediate level subject so I will be posting this thread with the following section containing links to the documentation for all the most important of these pre-defined variables. For a complete list of all the pre-defined variables you should check the docs here.

List
I'd recommend having a look at all of these but only once you get your head around all of the more basics concepts of php.

Expanding

What Next?

So you've reached the end of my PHP beginner mega tutorial and for this I congratulate you. My suggestion is that you find a project and stick with it, by doing this you'll be able to build your knowledge to a greater extent but in a way it will stick with you. Your first project is going to be sh*t. No exceptions. Don't go out trying to make the next Facebook right away but instead try a smaller simpler idea, it will still suck but it will be a much more enjoyable learning experience.

Useful Links
PHP Documentation
https://stackoverflow.com/
psr-2

Discover and read more posts from Jayaditya Gupta
get started
Enjoy this post?

Leave a like and comment for Jayaditya

3