• Welcome Guest to the new PlayerSquared! Please be aware the site is a work in progress & we'd appreciate your help in letting us know which features from the old site we're currently missing as well as report any bugs you find via this thread here: Bugs/Missing Features
  • If this is your first visit You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below. Sign up today to get the latest PS4 GameSaves, Game Mods and much more!

PHP Tutorial (Beginners Guide)

Algebra

Algebra
VIP User
December 10, 2018
14
6
0
3,285
This Thread Will Be Updated Everyday.

Hello and welcome to a standard PHP Tutorial series that will teach you or help you create or implement certain Web Applications.
I'd like to list some thing's about this tutorial series.

1. This is only a beginners guide into becoming a PHP Web Developer.
2. This is not a Full Stack Web Development series and any additional languages used like MySQL HTML5 or CSS or JavaScript will not
be explained in great detail. However if this tutorial series is successful enough to interest a specific amount of people with
the dedication of becoming a PHP Web Developer then I will do some more write ups on PHP. I'll create threads like problem solving strategies
PHP Error Handling, PHP Errors, & other general PHP topics will be started.
3. This is NOT for advanced PHP Developers.
4. Any questions I am glad to help once it is about the topic being discussed.
5. If you've any suggestions on what I could do better then please specify.

Okay so with those out of the way let's discuss what you will need for this tutorial series. The prerequisite's are listed below.

Prerequisite's


1. You need a brain, with good knowledge on how to operate a computer.
2. Basic HTML5, CSS, JavaScript knowledge would help during this tutorial.
3. Any Text Editor / IDE (Sublime Text Editor, Atom) whatever you want.
4. A Local host server. If you haven't got a localhost server set up don't worry I will be showing you how to set your own localhost web server up for development with PHP.
5. A positive mind set with the objective of learning how to code in PHP (Must want it from the heart) otherwise you'll lose interest.

Setting up a Localhost Server.

Let's set up a Localhost Server for PHP Web Development.

I will be setting this up on my Windows 10 Professional OS, however xampp does support Linux and OS X.

First we will download the application and disable UAC (User Account Control).

Here's a short video on 
Setting up everything on Windows 10 Professional

PHP Programming

Okay so now that we have our Server setup and everything working okay let's go a head and jump into programming in PHP.

PHP Tags & Comments


In PHP we do the following to initiate a PHP script and add some comments.
PHP:
<?php
      // Open our PHP script

      // Here we can write our code. Notice the "//" without the quotation marks We could also use "/* Comment */".
      // We use /* Comment */ when commenting multiple lines instead of manually typing "//" on each individual line.
      // Comment's can only be used inside our PHP script. In HTML5 you would need to use "<!-- These tags to display a comment -->"
      // We can use comment's various of way's. Below is a few ways we can put comments into use.

      // The users name that wins the race.
      $winner = "Derek";

      /**
       * Below we check if the winner of the race is Derek.
       * If the winner of the race is Derek we display Yay!.
       * If it is not Derek we echo Nay!.
      */

      if ($winner === "Derek") {
         echo "Yay!";
      }else {
         echo "Nay!";
      }

      // Closing our PHP script
?>

PHP Quotation Marks

In PHP we can use quotation marks to display text and work with data. I've shown some examples below.
PHP:
<?php
  // We can use both single and double quotation marks when displaying comments.

  // Example 1
  echo "Some random text.";

  // Example 2
  echo 'More random text.';

  // Both examples above give off the same results, however we can use double quotation marks to work with data.
  // The next example will display our string variable. I show 2 ways of displaying our string.
  // Example 3
  $name = "Derek";
  echo "My name is $name";

  // This way we concatenate our string to our current text being displayed.
  echo 'My name is ' . $name;

?>

PHP Variables

Variables in PHP represent a data type. There are different data types in PHP which we will be learning about each one individually.
Each variable in PHP has to begin with $ this indicates that it is a PHP variable. The $ symbol can only be specified like below.
PHP is also smart enough to know the data type you are trying to specify. (Int, String, Float, Object, Boolean)

I'll show a quick integer example which gives a numeric value to a variable specified as $value.
PHP:
<?php

  /**
   * Below is the correct way to name your variables although right now my naming convention isn't that great.
   * We are not allowed specify variables with a numerical value after the $ sign. See below.
   * $711 = "value";
   * The above demonstration would give an error. Test this out for yourself and play around with it.
   */

  $value = 711;
  $_value = 117;

?>

To create a variable we use the $ symbol, but to demonstrate what I'm trying to do. I've named the variables best I could to match the data types.
Example usage below. I will only be going over the basic ones.
PHP:
<?php
  // We can create multiple data types with a variable see below.

  // A String
  $username = "Algebra";

  // An Integer
  $age = 18;

  // A Float / Double Value
  $height = 5.12;

  // A Boolean
  $truth = true;

  // An Array
  $friends = array("Josh", "John", "David");
  // Another way of declaring an array of values: $friends = ["Josh", "John", "David"];
?>

Printing Text

We print text to the screen using echo. echo("Display text"); or echo "Display text";. Below is an example.
PHP:
<?php

  // Example 1
  echo "Displaying this text to the screen!";

  // Example 2
  echo("Displaying text to the screen");

  // Example 3
  print "This way of outputting is the same as echo except this has a return value (of 1) and echo has not.";

  // Example 4
  print("Echo is slightly faster than me!");

  /**
   * We can also use single quotation marks when displaying text to the screen.
   * I explained the differences between both in the PHP Quotation Marks section.
   */

  echo 'Single Quote output';

  // You can not use single quotes inside single quotes or double quotes inside double quotes.
  // We can use double quotes inside single quotes and single quotes inside double quotes.
  // However you can use them by adding a backslash, see below.

  echo 'Don\'t mess with me!';
  echo "\"Don't mess with me\"";

?>

Working With Arrays

Working with arrays in PHP will help us store and access our data more efficiently. We can use arrays to store key => value pairs.
Key => value pairs and arrays of data will be explained thoroughly, if you get perplexed just reply to the thread and I'll help.
PHP:
<?php
  // Below we set an array of values. Then we access these values inside our array, and then we output them.
  // Arrays start from 0 and iterate each time you add a value. Arrays can hold multiple data types.

  // Remember our "Quotation Marks" section, well the same is expected inside an array when working with strings.
  // I would suggest always using double quotation marks when working with an array of data.
  $team = array("Derek", "Age" => 34, "John");

  // We want to select the first string from our array of data.
  echo "$team[0] scored a goal!";

  // Now we want to select the last string from our array of data.
  echo $team[1] . ' scored an own goal and is now suffering from severe depression, his career is ruined.';

  // We now want to use our Key / Value pair to display Josh's age.
  echo "Josh is $team['Age'] years old!";

  /**
   * You might be confused about the arrays count. Since Age is before John, but since we are specifying a key => value pair
   * We must access that key's value using the name of our key, which is Age. So we would access this by typing $team['Age'].
   * This would then give us that keys value which is 34.
   */
?>

PHP IF Statements & Operators

In PHP we use logical if statements to determent what sort of result we want. There is a lot of ways we can use if statements, but I will only be demonstrating the standard usage for them.
PHP:
<?php
  // In this example we will compare two values a numerous of ways to display different results, using if statements.

  $dereks_age = 21;
  $johns_age = 18;

  // Comparing different types of results that may happen.
  // I use if, elseif, else in the example shown below.
  // If one of our checks is equal to true then it will only execute our code inside that block. The other conditions being checked will be skipped.

  if ($dereks_age > $johns_age) {
     echo "Derek is older than John";
  } elseif ($dereks_age != $johns_age) {
     echo "Derek is not the same age as John.";
  } elseif ($dereks_age == $johns_age) {
     echo "Derek is the same age as John.";
  } elseif ($dereks_age < $johns_age) {
     echo "Derek is younger than John.";
  } elseif ($johns_age <= $dereks_age) {
     echo "John is younger or the same age as Derek.";
  } elseif ($johns_age >= $dereks_age) {
     echo "John is the same age as Derek or older.";
  } else {
     echo "John is older than Derek.";
  }

  /**
   * In the above example we compared multiple results that could happen.
   * Some are the same results but others are not. We are basically asking if it's true or false.
   * The operators we used are listed below. We will go over some more of these in the future sections.
   * [color=blue]==, <=, >=, >, <, !=[/color]
   * Other logical operators we could have used. I would recommend searching up more about these.
   *[color=red] ||, &&, ![/color]
   */
?>

Switch Statement

Switch statements in PHP are used to work with data variables. Depending on what result is expected, we can use case's to determine the type of output we want. In our switch statement we iterate through each case.
PHP:
<?php
  // Below is an example usage of a switch statement.
  // There is 3 parts of a switch statement. There is the case, break, and default.
  // We discussed what case was in the above synopsis.
  // The break happens when we want to jump to the next case.
  // Finally we have our default. Default is used if we didn't receive the result we were expecting. So we set a default result.

  $age = 18;
  switch ($age) {
      case 15:
          echo "You are 15 years old!";
          break;
      case 16:
          echo "You are 16 years old!";
          break;
      case 17:
          echo "You are 17 years old!";
          break;
      case 18:
          echo "You are 18 years old!";
          break;
      default:
          echo "We could not determine your age!";
  }
?>

PHP For Loops

For loops in PHP are used to iterate through a variable. Depending on the amount of times we want it to iterate. We can even do infinite for loops that iterate infinitely.
PHP:
<?php
  // Below I demonstrate how a for loop operates.
  // I set a variable and iterate through it and increase the value of x on each iteration, see below.

  $x = 0;

  for ($i = 1; $i < 19; $i++) {
      echo ++$x . " of 18" . "<br>";
  }

  // The above for loop will iterate until our variable $i has a value of 19. Which will also echo the line of text 18 times.
  // The above code will echo a line like below 18 times.
  // 1 of 18
  // 2 of 18 etc
?>

PHP For Each Loops

For each loops in PHP can be used to iterate through an array and objects. We can assign an array / objects to a variable or a key => value pair. Below is a code example of how to implement the foreach construct.
PHP:
<?php
  // We will make two foreach constructs. The first example will assign an array to a variable and echo it's value.
  // Example 1:
  $foods = array("Tuna", "Chicken", "Pork", "Beef");

  foreach ($foods as $food) {
      echo "I Love $food";
  }

  // The next example we will use a key => value pair and display our name and age.
  // Example 2:
  $aboutMe = array("Derek" => 18, "Josh" => 21, "John" => 37);

  foreach ($aboutMe as $name => $age) {
      echo "Hey my names $name and my age is $age! <br>";
  }
?>

While Loops

While loops are fairly simple, we use them to check the condition of our expression being past. We check whether it returns true or false. If we pass true to our while loop we would be implementing an infinite loop, or if we set it to false the loop doesn't iterate at all.
PHP:
<?php
  // Below I set a numeric value, then use a while loop to iterate until our variable equals our expected value.
  $population = 0;

  while ($population <= 21) {
      echo "Added ". ++$population ." <br>";
  }

  // The above while loop will execute & output our text 21 times.
  // While loops are useful if we want to repeat our condition until our expected result is met.
?>

Do While Loops

Similar to a while loop, do while loop will execute until our condition is met.
PHP:
<?php
  // The usage is quite similar to the while loop.
  // However a do while loop always executes our code before our condition is met.
  // Unlike our while loops it first checks our condition then executes our code repeatedly until the condition is met.

  // Example:

  $population = 1;

  do {
      echo "Our population is " . $population++ . "<br>";
  } while ($population <= 21);

?>

Constants

We use Constants in PHP to define a specific value. We can access our constant in any part of our PHP script. Once it isn't defined inside a class. I will be discussing OOP in a different section of the PHP Tutorial Series.
PHP:
<?php
  // First we will show the correct way of assigning a constant value.
  // Our constants must be all UPPERCASE and each word divided by an underscore.

  define("AGE", 18);
  define("NAME", "John Doe");
  define("USERS_ADDRESS", "123 Hacker Way");

  // Here we concatenate our constants to our output being displayed.
  echo "My name is " . NAME . " I'm " . AGE . " years old. I live at " . USERS_ADDRESS;

  // The incorrect way of defining constants would be defining them as shown below.

  define("happy", "I'm not happy");
  define("lil_depressed", "Favorite rapper");
  define("50_cent", "2 fiddy");

  // Remember all our constant defined values must all be uppercase and start with a letter followed by an underscore, letters and numbers.
?>

PHP Functions

User Defined Functions in PHP is basically a way we can define code within the function being created and call it at a later time.

PHP:
<?php
  // Below we create a function that will assign a new value to our $age variable.

  $age = 18;
  $name = "";

  function oneYearLater() {
      $age = 19;
  }

  // We can call this function now since we have created it above.
  oneYearLater();

  // We can not call this function yet as it has not being created yet.
  // name();

  // However now that we have created our function we can call it after it has been parsed.
  function name() {
      $name = "Derek";
  }
  // This will now change our variable $name to the assigned value.
  name();

  // Next we will pass 2 parameters to a function.
  // In our function we will use the parameters in our output.

  function aboutMe($age, $name) {
      echo "My name is " . $name . " I am " . $age . " years old.";
  }

  // Since we assigned a value inside the above functions for each of our variables, we wont get the originally assigned values.
  // This will display My name is Derek I am 19 years old.
  
  aboutMe($age, $name);
?>

Now lets take a look at some built in PHP functions.

Lets start with strings. There is a lot of functions in PHP to work with strings lets take a look at some of the generally used ones.


PHP:
<?php
  $info = "My names Derek and I'm 19 years old!";

  // Okay so lets do some cool stuff with that very interesting string we declared.
  // First we will see if it contains my name Derek, if it does or doesn't we will echo the result.

  if (strpos($info, 'Derek') === false) {
      echo 'String does not contain Derek!';
  } else {
      echo 'String does contain Derek!';
  }

  // Okay so now we know how to check whether a string contains a specified string.
  // How do we check the length of a string?
  // Below we can count the length of a string. Lets store it in a new variable named $length.
  // Then we will echo its length!

  $length = strlen($info);
  echo "<br>The length of our string is " . $length;

  /**
   * You will probably wonder why I put a <br> tag. Well because earlier we echoed if the string contained the word Derek
   * Which it did so we break on to a new line.
   * Now we will search for Derek and replace it with Dylan. we can do this with a built in function.
  */

  $update_info = str_replace('Derek', 'Dylan', $info);
  echo '<br>' . $update_info;

  // The above should output My names Dylan and I'm 19 years old!
  // Next we can repeat a string. We can define how many times we want to repeat it check below.

  echo '<br>';
  $random = "Crazy<br>";
  echo str_repeat($random, 5);

  // Next I'm going to show how we can get a sub string. I will declare a new string and extract my name from it.
  // We give it a negative 5 because we are starting from the end of the string.
  // I will give two examples see below.

  $name = "My names Derek";
  echo substr($name, -5);

  echo '<br>';

  // Here we start at the beginning of the string and only return 5 characters.
  // Which will return Derek
  $name = "Derek is my name";
  echo substr($name, -16, 5);
?>

Lets take a look at some cool Maths functions built into PHP.

PHP:
<?php
  // First we will convert our numeric value into a binary value and print it.
  // Some great naming convention going on here folks. But remember this is just for demonstration purposes!
  $value = 19;

  // We convert our Numeric value by passing 1 parameter to the decbin() function, we also want an 8 digit return value.
  printf("%08d", decbin($value));

  // Now we will convert the binary string value to a decimal value. 
  $bin_value = decbin($value);

  printf("<br>%d", bindec($bin_value));

  // Lets explain what we just did.
  // First we declared our numeric value 19. Then we converted the numeric value to binary. We stored it in a variable named 
  // $bin_value, we then printed the numeric value using printf. 
  // What is %d? Think of this as a placeholder for our numerical digit. We then declare the value after our string.
  // Note that your variables being declared in printf must be in the correct format. See below as an example.

  $age = 19;
  $name = "Derek";
  printf("<br>My name is %s and my age is %d.", $age, $name);

  // This is correct using %s as declaring a string format and then %d declaring an integer to format. 
  // We only pass 2 arguments our $name and our $age. 
  // If $age was before $name we would get: My name is 19 and my age is 0. 
  // Remember you need to format it correctly especially when passing our variables. 
  // Another example would be passing 2 integers but not in the correct order. See below

  $games = 7;
  $consoles = 2;
  printf("<br>I have %d consoles but only %d games.", $games, $consoles);

  // We want to display: I have 2 consoles but only 7 games.
  // But we didn't declare our variables in the correct order so it will display: I have 7 consoles but only 2 games.
  // See below for the correct order.

  printf("<br>I have %d consoles but only %d games.", $consoles, $games);

  // Now lets take a look at converting a decimal value to a hex value then from hex to decimal.
  $age = 19;
  $max = "FF";

  echo "<br>My age in Hex is " . dechex($age);
  echo "<br>Max hex value is: " . hexdec($max);
?>
 
If you're on a Mac (like me) you can use this guide to setup a homebrew Apache2 & PHP environment, which also provides support for multiple versions of PHP (extremely useful as a developer).