PHP Beginner's Guide

56 minutes
1 year, 1 month ago
<p>## **Contents**</p><p>1. Introduction</p><p>2. Getting Started</p><p>3. Basic Syntax</p><p>4. Variables</p><p>5. Operators</p><p>6. Arrays</p><p>7. Control Structures</p><p>8. Functions</p><p>9. Pre-defined Variables</p><p>10. Expanding</p><p>## **Introduction**</p><p>What's PHP?</p><p>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.</p><p>What can it do?</p><p>PHP has a huge collection of uses such as:</p><p>- Database management</p><p>- Generating dynamic content on a page</p><p>- Handling data from forms</p><p>- Controlling and limiting site access to users</p><p>- Data encryption</p><p>So much more!</p><p>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.</p><p>## **Getting Started**</p><p>**Installing**</p><p>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 []( 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.</p><p>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](</p><p>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.</p><p>```</p><p>&lt;?php</p><p> echo "Welcome to PHP";</p><p>?&gt;</p><p>```</p><p>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".</p><p>Congratulations! You're now one step closer to becoming a PHP pro!</p><p>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.</p><p>## **Basic Syntax**</p><p>**PHP Tags**</p><p>All scripts start and end with these tags:</p><p>```</p><p>&lt;?php</p><p> //Code goes here.</p><p>?&gt;</p><p>```</p><p>The PHP tags can be placed anywhere in your document.</p><p>Here is an example where I have used a function called echo to print out "Hey" on to a web page.</p><p>```</p><p>&lt;?php</p><p> echo "Hey";</p><p>?&gt;</p><p>```</p><p>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.</p><p>**Echo**</p><p>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.</p><p>```</p><p>&lt;?php</p><p> echo "&lt;strong&gt;This will output strong text!&lt;/strong&gt;";</p><p>?&gt;</p><p>```</p><p>**Comments**</p><p>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.</p><p>```</p><p>&lt;?php</p><p> //This is a single line comment. It only comments this line</p><p> echo "Hello world";</p><p> /*</p><p> This is a multi-line comment. It comments anything between the constructs.</p><p> */</p><p>?&gt;</p><p>```</p><p>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.</p><p>## **Variables**</p><p>**Regular Variables**</p><p>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.</p><p>```</p><p>&lt;?php</p><p> $var_name = 10;</p><p>?&gt;</p><p>```</p><p>There are some important things you must remember when setting a variable name:</p><p>- The name of a variable must start with a letter or an underscore.</p><p>- Variable names are case sensitive (so $swag would not be the same as $SWAG).</p><p>- A variable name cannot start with a number.</p><p>- A variable name can contain only letters, numbers and underscores.</p><p>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.</p><p>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:</p><p>```</p><p>&lt;?php</p><p> $name = "Ciaran";</p><p> //Since I put in the quotation marks PHP knows that is a string.</p><p> echo $name;</p><p> //Now the echo construct goes and looks for variable $name and outputs it.</p><p>?&gt;</p><p>```</p><p>**Constants**</p><p>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.</p><p>To create a constant you use the define() function.</p><p>```</p><p>define(name, value, case-insensitive) </p><p>```</p><p>Parameters:</p><p>- name: Specifies the name of the constant.</p><p>- value: Specifies the value of the constant.</p><p>- case-insensitive: Should the constant name be case sensitive? This is defaulted to false.</p><p>```</p><p>&lt;?php</p><p> define("HELLO", "Hello there friend.");</p><p> echo HELLO;</p><p> //Outputs "Hello there friend."</p><p>?&gt;</p><p>```</p><p>Example using case sensitive:</p><p>```</p><p>&lt;?php</p><p> define("HELLO", "Hello there friend.", true);</p><p> echo hello;</p><p> //Outputs "Hello there friend."</p><p>?&gt;</p><p>```</p><p>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.</p><p>```</p><p>&lt;?php</p><p> const CONSTANT = value;</p><p>?&gt;</p><p>```</p><p>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.</p><p>**Data Types**</p><p>A data type is the type of information stored within a variable. PHP has 8 main data types listed here:</p><p>- String</p><p>- Integer</p><p>- Float</p><p>- Boolean</p><p>- Array</p><p>- Object</p><p>- NULL</p><p>- Resource</p><p>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. </p><p>```</p><p>&lt;?php</p><p> $inta = 11; //Positive integer</p><p> $intb = -11; //Negative integer</p><p>?&gt;</p><p>```</p><p>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.</p><p>```</p><p>&lt;?php</p><p> $stringa = "Hello there buddy."; //You could also replace the " with '.</p><p> $stringb = "Nice weather today.";</p><p> echo $stringa . $stringb; //This will add b onto the end of a and output them.</p><p>?&gt;</p><p>```</p><p>A float (floating point mumber) is a numeric variable like an integer except it includes a decimal.</p><p>```</p><p>&lt;?php</p><p> $a = 107.5;</p><p>?&gt;</p><p>```</p><p>A boolean is a variable that can be represented in two possible states: TRUE or FALSE.</p><p>```</p><p>&lt;?php</p><p> $x = TRUE;</p><p> $y = FALSE;</p><p>?&gt;</p><p>```</p><p>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.</p><p>**Variable Scope**</p><p>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.</p><p>```</p><p>&lt;?php</p><p> $var1 = 50; //This sets a variable with global scope.</p><p> function printNum() //Defining a function (will explain this more later)</p><p> {</p><p> $var1 = 49; //Sets this variable with a local scope.</p><p> echo $var1; //Will output 49 as it checks for variables with a local scope.</p><p> }</p><p> printNum(); //Calling the function.</p><p>?&gt;</p><p>```</p><p>## **Operators**</p><p>**Arithmetic**</p><p>Arthimetic operators work with numeric values to perform common arthimetic operations.</p><p>- Addition | $a + $b</p><p>- Subtraction | $a - $b</p><p>- Multiplication | $a * $b</p><p>- Division | $a / $b</p><p>- Modulus | $a % $b</p><p>- Exponentiation | $a \*\* $b</p><p>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:</p><p>```</p><p>&lt;?php</p><p> $a = 14;</p><p> $b = 3;</p><p> echo $a % $b; // Outputs 2 </p><p>?&gt;</p><p>```</p><p>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:</p><p>```</p><p>&lt;?php</p><p> $a = 3;</p><p> $b = 2;</p><p> echo $a ** $b; //Outputs 9</p><p>?&gt;</p><p>```</p><p>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.</p><p>```</p><p>&lt;?php</p><p> // Post increments.</p><p> $a++; // equivalent to $a = $a + 1</p><p> $a--; // equivalent to $a = $a - 1</p><p>?&gt;</p><p>```</p><p>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.</p><p>```</p><p>&lt;?php</p><p> $x = 5; $y = $x++; //$x = 6 and $y = 5 </p><p> $x = 5; $y = $++x; //$x = 6 and $y = 6</p><p>?&gt;</p><p>```</p><p>**Assignment**</p><p>Assignment operators work with numeric values to write values to variables.</p><p>```</p><p>&lt;?php</p><p> $x = 42;</p><p> $x = $num1</p><p>?&gt;</p><p>```</p><p>Assignment operators can also work with arithmetic operators.</p><p>```</p><p>&lt;?php</p><p> $x = 5;</p><p> $x += 10; // You can replace the + with any other arithmetic operator.</p><p> echo $x;</p><p> // Outputs 15</p><p>?&gt;</p><p>```</p><p>**Comparison**</p><p>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:</p><p>- Equal | ==</p><p>- Identical | ===</p><p>- Not Equal | !=</p><p>- Not Equal | &lt;&gt;</p><p>- Not Identical | !==</p><p>- Greater Than | &gt;</p><p>- Greater Than or Equal To | &gt;=</p><p>- Less Than | &lt;</p><p>- Less Than or Equal To | &lt;=</p><p>**Logical**</p><p>Logical operators are used to combine conditional statements. Bellow is a list of all of them:</p><p>- And | and</p><p>- Or | or</p><p>- Xor | xor</p><p>- And | &amp;&amp;</p><p>- Or | ||</p><p>- Not | !</p><p>## **Arrays**</p><p>**Numeric Arrays**</p><p>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:</p><p>```</p><p>&lt;?php</p><p> $myfirstarray = array(</p><p> item1 =&gt; "value1",</p><p> item2 =&gt; "value2",</p><p> item3 =&gt; "value3",</p><p> )</p><p> //OR</p><p> $array = array("value1", "value2", "value3");</p><p> // You can also assign the index manually like this. </p><p>?&gt;</p><p>```</p><p>We access an element by referencing its </p><p>```</p><p>&lt;?php</p><p> echo $dogs[1]; // Will echo Lola.</p><p>?&gt;</p><p>```</p><p>**Associative Arrays**</p><p>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:</p><p>```</p><p>&lt;?php</p><p> $characters = array("Kenny"=&gt;"9","Stan"=&gt;"10","Cartman"=&gt;"8");</p><p> //or</p><p> $characters['Kenny'] = "9";</p><p> $characters['Stan'] = "10";</p><p> $characters['Cartman'] = "8";</p><p> // both give the same result</p><p>?&gt;</p><p>```</p><p>To access the values of this kind of array, you use the named keys instead of the usual numeric value.</p><p>```</p><p>&lt;?php</p><p> echo $characters['Cartman'];</p><p>?&gt;</p><p>```</p><p>**Multi-Dimensional Arrays**</p><p>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:</p><p>```</p><p>&lt;?php</p><p> $people = array(</p><p> 'friends'=&gt;array('Hunt','Draig')</p><p> 'enemies'=&gt;array('Josh','Silver')</p><p> 'family'=&gt;array('Sinead','Declan')</p><p> );</p><p>?&gt;</p><p>```</p><p>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.</p><p>```</p><p>&lt;?php</p><p> echo $people['friends'][0]; //Outputs Hunt.</p><p> echo $people['family'][1]; //Outputs Declan.</p><p>?</p><p>```</p><p>**Control Structures**</p><p>If Else Statements</p><p>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:</p><p>```</p><p>&lt;?php</p><p> if(condition){</p><p> //run this if condition is true</p><p> }else{</p><p> //run this code if condition is false, you can also remove this else and just have the if.</p><p> }</p><p>?&gt;</p><p>```</p><p>Now let's look at an example using some actual code:</p><p>```</p><p>&lt;?php</p><p> $x = 2;</p><p> $y = 4;</p><p> if($x == $y){</p><p> echo $x;</p><p> }else{</p><p> echo $y;</p><p> }</p><p>?&gt;</p><p>```</p><p>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. </p><p>Elseif Statements</p><p>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:</p><p>```</p><p>&lt;?php</p><p> if(condition){</p><p> //run this if condition is true</p><p> }elseif(condition){</p><p> //run this code if second condition is true</p><p> }else{</p><p> //run this code if condition is false</p><p> }</p><p>?&gt;</p><p>```</p><p>And once again here is a code example:</p><p>```</p><p>&lt;?php</p><p> $x = 2;</p><p> $y = 4;</p><p> $z = 3;</p><p> if($x == $y){</p><p> echo $x;</p><p> elseif($x == $z){</p><p> echo $z;</p><p> }else{</p><p> echo $y;</p><p> }</p><p>?&gt;</p><p>```</p><p>**While Loop**</p><p>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:</p><p>```</p><p>&lt;?php</p><p> while(conditon){</p><p> //so until the condition is false do this code</p><p> }</p><p>?&gt;</p><p>```</p><p>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. </p><p>Now let's have a look at an actual code example:</p><p>```</p><p>&lt;?php</p><p> $apple = 20;</p><p> $pear = 10;</p><p> while($apple &gt; $pear){ //While apple is bigger than pear.</p><p> echo $pear; // output pear</p><p> $pear++; //add one to pear so eventually the condition becomes false and the loop exits </p><p> }</p><p>?&gt;</p><p>```</p><p>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.</p><p>```</p><p>&lt;?php</p><p> do{</p><p> //code</p><p> }while (condition);</p><p>?&gt;</p><p>```</p><p>```</p><p>&lt;?php</p><p> $x = 0;</p><p> do{</p><p> $x++;</p><p> }while ($x==5);</p><p> echo $x;</p><p>?&gt;</p><p>```</p><p>**For/Foreach Loop**</p><p>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.</p><p>```</p><p> for(init; test; increment){</p><p> //code</p><p> }</p><p>?&gt;</p><p>```</p><p>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.</p><p>```</p><p>&lt;?php</p><p> for($a; $a &gt; 6; $a++){</p><p> echo $a;</p><p> }</p><p>?&gt;</p><p>```</p><p>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. </p><p>```</p><p>&lt;?php</p><p> $numbers = array(1,2,3);</p><p> foreach($numbers as $num =&gt; $value){</p><p> echo $value;</p><p> }</p><p>?&gt;</p><p>```</p><p>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. </p><p>**Switch Statement**</p><p>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.</p><p>```</p><p>&lt;?php</p><p> $animal = "Dog";</p><p> switch($animal){</p><p> case "Cat":</p><p> echo "your animal is a cat";</p><p> break; </p><p> case "Dog":</p><p> echo "your animal is a dog";</p><p> break;</p><p> case "Fish":</p><p> echo "your animal is a fish";</p><p> break;</p><p> default:</p><p> echo "your animal doesnt exist";</p><p> }</p><p>?&gt;</p><p>```</p><p>**Ternary Conditionals**</p><p>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:</p><p>```</p><p>&lt;?php</p><p> variable = condition ? trueValue : falseValue;</p><p>?&gt;</p><p>```</p><p>Now let's see a working example.</p><p>&lt;?php</p><p> $var = 7;</p><p> $var = $var &lt; 10 ? 11 : 7;</p><p>?&gt;</p><p>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.</p><p>**Include and Require**</p><p>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:</p><p>```</p><p>&lt;?php</p><p> include 'filename.php';</p><p>?&gt;</p><p>```</p><p>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.</p><p>## **Functions**</p><p>**User Defined**</p><p>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. </p><p>```</p><p>&lt;?php</p><p> function helloworld() {</p><p> //Code to run goes in here.</p><p> echo "Hello world.";</p><p> }</p><p> helloworld(); //Runs the function.</p><p>?&gt;</p><p>```</p><p>Function names must begin with a letter or an underscore but may contain special characters and numbers. They are not case sensitive.</p><p>**Parameters**</p><p>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.</p><p>```</p><p>&lt;?php</p><p> function multiply($num1, $num2) {</p><p> echo $num1 * $num2;</p><p> }</p><p> </p><p> multiply(3,2);</p><p> //Outputs 6.</p><p>?&gt;</p><p>```</p><p>**Return**</p><p>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.</p><p>```</p><p>&lt;?php</p><p> function multiply($num1, $num2) {</p><p> $answer = $num1 * $num2;</p><p> return $answer;</p><p> }</p>


You must login to comment