PHP Tutorial For Beginners - NextGenUpdate
THREAD: PHP Tutorial For Beginners
  1. 06-24-2018, 06:50 PM
    #1
    Algebra's Avatar
    Algebra
    mov eax, 69
    Algebra's Avatar
    Algebra
    mov eax, 69
    292
    Posts
    8,480
    Reputation
    Dec 2014
    NextGenUpdate
    Sponsored Links

    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
    Spoiler:

    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.
    Spoiler:

    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 everything up on Windows 10 Professional.




    PHP Programming
    Spoiler:

    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
    Spoiler:

    In PHP we do the following to initiate a PHP script and add some comments.
    Code:
    <?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
    Spoiler:

    In PHP we can use quotation marks to display text and work with data. I've shown some examples below.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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.
    Code:
    <?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
    Spoiler:

    We print text to the screen using echo. echo("Display text"); or echo "Display text";. Below is an example.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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.
       * ==, <=, >=, >, <, !=
       * Other logical operators we could have used. I would recommend searching up more about these.
       * ||, &&, !
       */
    ?>


    Switch Statement
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    Similar to a while loop, do while loop will execute until our condition is met.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Spoiler:

    Code:
    <?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.
    Spoiler:

    Code:
    <?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.
    Spoiler:

    Code:
    <?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);
    ?>


    Last edited by Algebra; 08-28-2018 at 04:30 PM.

  2. Sponsored Links
  3. The Following 3 Users Say Thank You to Algebra For This Useful Post:

    , ,

  4. 06-26-2018, 07:21 AM
    #2
    JB's Avatar
    JB
    Remember, no Russian
    JB's Avatar
    JB
    Remember, no Russian
    539
    Posts
    14,209
    Reputation
    Dec 2009
    NextGenUpdate
    Going to add my two cents early here - if you really are interested in PHP, follow the industry standards and abide by certain ideologies. [Only registered and activated users can see links. ] and [Only registered and activated users can see links. ] will really improve code readability (and therefore maintainability), and I strongly recommend it to anyone who works with PHP at any level. The standards take 5 minutes to learn, but will save you hours down the line. You can thank me later.

    Don't get in to the habit of closing your PHP tag if you don't need to, either. If your script ends with PHP code, you don't need the final ?> tag. In fact, it's recommended NOT to have it, as it can cause unnecessary whitespace (which can and will affect header output etc.).

    PHP 5 is nearly EOL - focus on programming for PHP 7. It's much better and faster than PHP 5.

    Remember that Windows handles PHP slightly differently to Mac/Linux - if you can, try and use one of these systems, otherwise you'll probably run into issues pushing stuff to a live server.

    I highly recommend against using XAMPP on Mac/Linux - you can use package managers to install HTTPD, MySQL and PHP (homebrew on Mac, yum/apt on Linux).

    Test, test, test! It's extremely easy to assume your code will "just work" - PHP can change greatly from version to version. ALWAYS fully test out your code. Again, you can thank me later.

    You don't need to reinvent the wheel - [Only registered and activated users can see links. ] is a package manager for PHP that has a library for just about everything. [Only registered and activated users can see links. ].

    Try not to write huge files - you can easily include or require another file. It's much cleaner that way.

    Only use namespacing if necessary. If you're working on an MVC framework or a large application, namespacing is the way to go (especially if it uses composer).

    There are hundreds of great resources out there and places to ask questions. [Only registered and activated users can see links. ] is a great resource for developers of any language. Don't be scared to ask for help, it will make you a much better developer.

    I'm also happy to answer any questions. I have 7 years of experience with PHP and know most of the ins and outs of the language. I also work as a professional full stack web developer and sysadmin.
    Last edited by JB; 06-26-2018 at 07:26 AM.

  5. The Following 2 Users Say Thank You to JB For This Useful Post:

    ,

  6. 06-26-2018, 07:37 AM
    #3
    Algebra's Avatar
    Algebra
    mov eax, 69
    Algebra's Avatar
    Algebra
    mov eax, 69
    292
    Posts
    8,480
    Reputation
    Dec 2014
    NextGenUpdate
    Originally Posted by JB View Post
    Going to add my two cents early here - if you really are interested in PHP, follow the industry standards and abide by certain ideologies. [Only registered and activated users can see links. ] and [Only registered and activated users can see links. ] will really improve code readability (and therefore maintainability), and I strongly recommend it to anyone who works with PHP at any level. The standards take 5 minutes to learn, but will save you hours down the line. You can thank me later.

    Don't get in to the habit of closing your PHP tag if you don't need to, either. If your script ends with PHP code, you don't need the final ?> tag. In fact, it's recommended NOT to have it, as it can cause unnecessary whitespace (which can and will affect header output etc.).

    PHP 5 is nearly EOL - focus on programming for PHP 7. It's much better and faster than PHP 5.

    Remember that Windows handles PHP slightly differently to Mac/Linux - if you can, try and use one of these systems, otherwise you'll probably run into issues pushing stuff to a live server.

    I highly recommend against using XAMPP on Mac/Linux - you can use package managers to install HTTPD, MySQL and PHP (homebrew on Mac, yum/apt on Linux).

    Test, test, test! It's extremely easy to assume your code will "just work" - PHP can change greatly from version to version. ALWAYS fully test out your code. Again, you can thank me later.

    You don't need to reinvent the wheel - [Only registered and activated users can see links. ] is a package manager for PHP that has a library for just about everything. [Only registered and activated users can see links. ].

    Try not to write huge files - you can easily include or require another file. It's much cleaner that way.

    Only use namespacing if necessary. If you're working on an MVC framework or a large application, namespacing is the way to go (especially if it uses composer).

    There are hundreds of great resources out there and places to ask questions. [Only registered and activated users can see links. ] is a great resource for developers of any language. Don't be scared to ask for help, it will make you a much better developer.

    I'm also happy to answer any questions. I have 7 years of experience with PHP and know most of the ins and outs of the language. I also work as a professional full stack web developer and sysadmin.
    I couldn't agree more with you on this one. I hope other people contribute like you have.
  7. 07-09-2018, 09:39 AM
    #4
    1
    Posts
    10
    Reputation
    Jul 2018
    NextGenUpdate
    Thanks for the codes.
    Originally Posted by Algebra View Post
    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 [Only registered and activated users can see links. ] 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
    Spoiler:

    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.
    Spoiler:

    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 everything up on Windows 10 Professional.




    PHP Programming
    Spoiler:

    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
    Spoiler:

    In PHP we do the following to initiate a PHP script and add some comments.
    Code:
    <?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
    Spoiler:

    In PHP we can use quotation marks to display text and work with data. I've shown some examples below.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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.
    Code:
    <?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
    Spoiler:

    We print text to the screen using echo. echo("Display text"); or echo "Display text";. Below is an example.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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.
       * ==, <=, >=, >, <, !=
       * Other logical operators we could have used. I would recommend searching up more about these.
       * ||, &&, !
       */
    ?>


    Switch Statement
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    Similar to a while loop, do while loop will execute until our condition is met.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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
    Spoiler:

    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.
    Code:
    <?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);
    ?>

  8. 07-27-2018, 05:44 AM
    #5
    Algebra's Avatar
    Algebra
    mov eax, 69
    Algebra's Avatar
    Algebra
    mov eax, 69
    292
    Posts
    8,480
    Reputation
    Dec 2014
    NextGenUpdate
    Originally Posted by jacklinj068 View Post
    Thanks for the codes.
    They are code samples which can help you learn.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •