Practical PHP: Master the Basics and Code Dynamic Websites

Code Your Very Own Dynamic Websites by Learning PHP Through Real-World Application & Examples
4.5 (3,223 ratings)
Instead of using a simple lifetime average, Udemy calculates a
course's star rating by considering a number of different factors
such as the number of ratings, the age of ratings, and the
likelihood of fraudulent ratings.
66,927 students enrolled
Start Learning Now
  • Lectures 45
  • Length 6.5 hours
  • Skill Level All Levels
  • Languages English
  • Includes Lifetime access
    30 day money back guarantee!
    Available on iOS and Android
    Certificate of Completion
Wishlisted Wishlist

How taking a course works


Find online courses made by experts from around the world.


Take your courses with you and learn anywhere, anytime.


Learn and practice real-world skills and achieve your goals.

About This Course

Published 7/2014 English

Course Description

Learn How to Code Dynamic Websites with PHP for absolute beginners!

This course is a total beginners guide to coding dynamic websites with PHP so you need no prior knowledge or experience with PHP — although, it is a good idea if you know some HTML & CSS. (My beginner's guide Build a Website from Scratch with HTML & CSS will teach you everything you need to know about HTML & CSS.)

Practical Hands-on Approach

My approach with this course, like many of my courses, is to take a practical "hands on" approach. While there will be some theory involved — every single lesson requires you to get your hands dirty and exercise what you've learned in that specific lesson. I find this to be the best approach, because you're able to retain much more of what you learned, and therefore, get up and running with maximizing your practical knowledge of PHP quickly!

Why Should I Learn PHP?

So — why learn PHP? Well, PHP is a very powerful scripting language used by millions of websites. Some of the most popular websites and frameworks utilize PHP to build their dynamic websites. PHP works very well with HTML, and therefore will allow you to start coding dynamic websites quickly without having to learn some of the more complicated scripting languages out there.

You Will Love This Course

I think you're going to love this course, and you're going to especially love what you're going to learn. When I first started learning PHP, I couldn't wait to start implementing what I learned into my websites! I think you'll feel the same.

It's Totally Free!

Also, I am excited to be offering this course absolutely free for three reasons:

  1. I don't want a purchasing decision to get in the way of you learning what I have to offer in this course.
  2. I want as many people as possible to be able access the content.
  3. I want to give you learning material so good that it should cost money.

The Final Project

Throughout the course you will be building a handful of dynamic PHP examples, but in the last section of the course, we will build a dynamic website for a (fictional) restaurant.

So, I invite you to join me in learning how to Code Dynamic Websites with PHP!

Let's do this.

What are the requirements?

  • Internet Connection
  • Willingness to be awesome
  • Determination
  • Sense of humour
  • Code Editor
  • Some additional (free) tools

What am I going to get from this course?

  • By the end of this course, you will have a thorough understanding of the PHP fundamentals
  • Upon completion, you will have coded a handful of useful dynamic PHP examples
  • In the last section of this course, you focus on building a dynamic website for a restaurant
  • By the end of this course, you will be so excited about your newly acquired PHP skills and want to start converting all your websites to PHP!

Who is the target audience?

  • Total Beginners
  • Web Design Students
  • Graphic Designers
  • Entrepreneurs
  • Business Owners
  • Bloggers
  • Web Designers

What you get with this course?

Not for you? No problem.
30 day money back guarantee.

Forever yours.
Lifetime access.

Learn on the go.
Desktop, iOS and Android.

Get rewarded.
Certificate of completion.


Section 1: Introduction
Hey everybody, welcome to Code Dynamic Websites with PHP!

My name is Brad Hussey and for the next little while, I'm going to be your personal instructor, and I will be teaching you how to hand code PHP!

This course is a Total Beginner's Guide to Coding Your Very Own Dynamic Websites with PHP, so you need no prior knowledge or experience — although it's a good idea that you know some HTML (my beginner's guide "Build a Website from Scratch with HTML & CSS" will get teach you everything you need to know).

My approach with this course, like many of my courses, is to take a practical "hands on" approach. While there will be *some* theory involved — every single lesson requires you to get your hands dirty and exercise what you've learned in that specific lesson. I find this to be the best approach, because you're able to retain much more of what you learned, and therefore, get up and running with maximizing your practical knowledge of PHP quickly!

So — why learn PHP? Well, PHP is a very powerful scripting language used by millions of websites. Some of the most popular websites and frameworks utilize PHP to build their dynamic websites. PHP works very well with HTML, and therefore will allow you to start coding dynamic websites quickly without having to learn some of the more complicated scripting languages out there.

I think you're going to love this course, and you're going to especially love what you're going to learn. When I first started learning PHP, I *couldn't wait* to start implementing what I learned into my websites! I think you'll feel the same.

Also, I am excited to be offering this course absolutely free for three reasons:

  1. I don't want a purchasing decision to get in the way of you learning what I have to offer in this course.
  2. I want as many people as possible to be able access the content.
  3. I want to give you learning material so good that it should cost money.

So, I invite you to join me in learning how to Code Dynamic Websites with PHP!

Let's do this.

Lecture 2: What is PHP?

PHP is one of the most (if not the most popular) server-side programming language on the web today, with more than 240 million websites using it (as of January 2013 — according to Wikipedia).

Websites like Google, Apple, Facebook and YouTube utilize PHP. Popular Content Management Systems (CMS) like Wordpress, Drupal, Joomla and Expression Engine all rely on PHP.

PHP stands for "Hypertext Preprocessor" — I know, right? I don't get it either...

PHP can be used as a stand-alone programming language to create robust applications, or it can be used within HTML code to create dynamic websites (which is the goal of this course).

PHP runs on a "server", and in order to use PHP on your own computer when developing a website, you'll need to have a server installed on your machine — don't worry about this part, it's quick & painless to get set up, and it doesn't cost you a penny.

I'll be covering the tools you'll need in an upcoming lecture.

Also, I will be frequently referencing throughout the duration of this course, and I recommend you bookmark it for easy access.

Stay tuned, because in the next lecture I'll give you a quick rundown of some of the cool things PHP can do!

See you there!


Lecture 3: What does PHP do?

PHP can do a whole bunch of really neat things, such as:

  • Access information typed into a web form and do something with it, like: Send an email, navigate to a specific page based on the info submitted in the form, create a user account, log a user in, etc.
  • Find out what browser and operating system your visitors are using.
  • Display alternate versions of a web page to users who are using mobile devices, or specific browsers (like Internet Explorer).
  • Do math!
  • And most importantly (in my opinion), create templates for your website so you don't have to hand-code your headers, footers, and sidebars for every single page!

There is so much that PHP can do, but I don't want to go into all the details right now, because I'd like to show you by jumping right in — I think it's much more fun that way!

Next up: You're going to need to have some specific tools in order to get the best out of your PHP learning experience. I'll cover those in the next lecture.

See you there!


Lecture 4: Tools to Get Started

As I mentioned before, because PHP is a "server-side programming language" it requires a server in order to run. Now, I don't mean a physical server that costs thousands of dollars and takes up an entire closet — I mean a virtual server that can run on your computer. The great thing about this is that there are a number of great free options out there.

If you're on a Mac, I suggest using MAMP. MAMP stands for "Mac Apache – MySQL – PHP" — however, they've recently developed a Beta version for Windows, so the Windows version stands for "My Apache – MySQL – PHP". If you're on a Windows machine, I recommend trying the Windows-version of MAMP as well — keep in mind that it's in Beta at the time of the recording of this video, so there may be some bugs they're working out.

Alternatively, both Mac & PC users can try something like AMPPS, but I will be using MAMP so it may be easier for you to follow along.

In the interest of full disclosure: Please keep in mind that some of the following resources are my affiliate links, and I’ll earn a small commission should you decide to make a purchase — at absolutely no cost to you! Keep in mind that I either have thorough experience with the following tools & websites, or have heard great things about them, and I am only recommending them because they have helped me succeed in my business, or are incredibly useful. Don’t spend your money on any products or resources unless you think they will help you, or further you in your learning experience.

My Most Recommended Tool

Coda 2 for Mac

The next tool you're going to need is a code editor. If you're serious about coding, or you want to start out with a solid tool to code with, I strongly recommend Coda 2 for Mac. A beautiful User Interface with tabbed navigation, a super sidebar, and a simple layout. The features are outrageous and extensive, with code folding, smart complete, auto indentation, GIT integration, a built-in terminal, iCloud support — to name a few. The features seem to be endless. I use Coda 2 for all of my courses & tutorials, and if you decide to use Coda 2 as your editor of choice, it would greatly benefit you when taking my courses. The price of the editor weighs in at $75, but there is a 7-day unlimited trial — which is plenty of time to complete this course!

However, there are more options out there. Here are a few you might consider:

For both Mac & Windows

  • Sublime Text
  • A full fledged code editor that features side-by-side mode for comparing documents, full screen mode, and a whole bunch of other great features. One of the best editors out there, and if I didn't love Coda 2 so much I would use this one. The price tag for Sublime Text is $70, but comes with a free trial.

    For Windows

  • Notepad++
  • Notepad++ is a free (as in "free speech" and also as in "free beer") source code editor and Notepad replacement that supports several languages. A solid Windows-based code editor!

    For Mac

  • Espresso
  • A sexy code editor that looks beautiful, and performs just as beautifully. Espresso claims to "turbo-charge your workflow". It features extensive language support, powerful smart snippets, code folding, real-time live styling, and so much more. I used to use Espresso exclusively, and I strongly recommend it. Espresso's price tag is $75, but also has a free trial.


    TextWrangler is a simple, barebones, text editor. It handles code well, but is meant for hand-coding with no frills. It's a good practise to learn how to hand code the "no frills" way if you're just starting out with learning how to code. It's free, too!


    The big brother to TextWrangler, BBEdit has a much more impressive feature set, much like the features listed in the code editors I previously mentioned. Price: $49.99, but free to try.


    A minimal code editor that allows multitasking, auto-code completion, syntax highlighting and more. I've never used it personally, but it seems to be a popular choice. The great thing about this one is it's only $5.99.


    I suggest using a modern browser, like Google Chrome, Apple Safari or Firefox. I will be using Chrome throughout this course.

    Domain Names & Web Hosting

    It's not required for this course, but it's a good idea to have a domain name & hosting account ready as later in the course we will be touching on how to upload your website live on the web.

    My most recommended hosting provider is Justhost. I use them for all of my websites, and have been a happy customer for nearly 7 years. I recommend these guys to all of my clients, my students, my family and friends. If you’re looking to start your very first website, or are looking for a reliable hosting provider — look no further. You get a free domain name for life, great customer service, unlimited domains, unlimited email accounts, unlimited GBs of space, an anytime money back guarantee and my favourite part: You can set up a blog website in minutes with 1-click WordPress Install. These guys are awesome!

    If you're looking to purchase a domain name, I recommend GoDaddy. I use GoDaddy to purchase all of my domain names, as it’s one of the best (if not, the best) website to find & purchase your domain names.

    Learning HTML & CSS

    If you're unfamiliar with HTML & CSS, I strongly recommend you pick up some basic skills before going forward with this course, as you might get lost in some of the concepts without HTML knowledge. Lucky for you, I have a total beginner's course called "Build a Website from Scratch with HTML & CSS" and it will get you up and running quickly. I'll also give you 50% off if you use the Coupon Code "DYNAMICPHP".

    That's all for important tools & resources at this point. I recommend bookmarking my Resources page at for reference, as I frequently update that page with the helpful tools I use to make my life a little easier.

    Thanks for hanging in there! Next up, we're diving into PHP basics!

    See you there.


    Lecture 5: The Course Files

    You may download the course files, absolutely free, using the following link:

    2 questions

    Testing your short-term memory.

    Section 2: PHP Basics

    Lecture 6: Your First PHP Web Page

    In this lecture we're going to be learning how to set up a virtual server to run your very first PHP web page. How exciting!


    Lecture 7: PHP Syntax

    In this lecture we're going to be learning a little bit about the basic syntax of PHP programming. It's a quick lecture, but very necessary in order to get started on the right foot.


    Lecture 8: PHP Variables

    Think of a variable as a bucket. Literally, a bucket. That bucket can hold stuff in it — like food, or dirt. In PHP, variables are buckets, but instead of holding food or dirt, they hold information — like numbers, text, images, or logic! All you need to know at this point is that variables are buckets that store information for later use. We'll get to how we actually use the variables in an upcoming lecture.

    The basic syntax of a variable is a dollar sign ($) directly followed by a variable name (using text, with no spaces), then an equal sign, followed by the contents of the variable, ending with a semi-colon. Ex: $variable_name = 'my first variable';

    There are 4 basic variable types, and each type of variable (or "bucket") is meant to hold specific information. Watch the lecture or download the PDF to learn what the 4 basic variable types are.


    Lecture 9: More Variables

    In this lecture, we cover a couple more examples of the basic usage of PHP variables.


    Lecture 10: Defining Constants

    A constant is similar to a variable in the sense that you can store information in a keyword that can be used throughout your web page. However, the value of a constant cannot be changed, unlike a variable. It's literally "constant".

    It's also worth noting that constants are case-sensitive and are written in ALL CAPS by convention. Here's how you define a constant in PHP:

    define("TITLE", "Defining Constants");

    To display a constant on your page, you can echo it using PHP, like this:

    <?php echoTITLE; ?>


    Lecture 11: Get Your Hands Dirty!

    In this lecture we put in to practice everything we've learned so far:

    • PHP Variables
    • PHP Constants

    Simple and straightforward, you will be able to see the benefits of using variables and constants right away!

    Section 3: PHP Arrays

    Lecture 12: Arrays

    Sometimes you'll want to store more than one value within your variables. With an array, you can do just that! Arrays allow you to store multiple values within a variable.

    For example, I think moustaches are neat. There are many kinds of moustaches! Using individual variables, I can store each moustache in their own, like so:

    $moustache1 = "Handlebar";

    $moustache2 = "Salvador Dali";

    $moustache3 = "Fu Manchu";

    But, I'd like to keep things neat n' tidy and have all my moustaches in a single variable. So I'll use an array, like so:

    $moustaches= array("Handlebar", "Salvador Dali", "Fu Manchu");

    Each value is automatically assigned a "key" in the array, so we can grab a specific value when we need it. We'll touch on keys later, but by default, each value has a numeric key assigned to it.

    So for example, "Handlebar" is 1, "Salvador Dali" is 2, and "Fu Manchu" is 3. Here's the catch though — the numbers start at 0, not 1. So, "Handlebar" is actually 0, etc.

    If we want to grab a value out of an array and display it on our web page, we just reference the array and the key associated with the value we want to display, like so:


    echo $moustaches[0]; // this will display "Handlebar"

    echo $moustaches[1]; // this will display "Salvador Dali"

    echo $moustaches[2]; // this will display "Fu Manchu"


    Arrays are pretty powerful, and there's a lot more to them. So stay tuned!


    Lecture 13: Associative Arrays

    Remember how PHP automatically assigns a number to each item in an array? Well, using Associative Arrays you can give a custom name to the key, rather than using a number. It looks like this:

    $handlebar = array(

    name => "Handlebar",

    creep_factor => "High",

    avg_growth_days => 14


    Now, let's say I wanted to display specific information from the array. I would do so by simply referring to a custom key in the array, like this:

    <?php echo$handlebar[creep_factor]; ?>


    Lecture 14: Multi-Dimensional Arrays

    This is where we start getting crazy! We can harness the true potential of arrays by using multi-dimensional arrays — which is simply an array that is comprised of multiple arrays!

    $moustaches = array (

    array (

    "name" => "Handlebar",

    "creep_factor" => "High",

    "avg_growth_days" => 14


    array (

    "name" => "Salvador Dali",

    "creep_factor" => "Extreme",

    "avg_growth_days" => 62


    array (

    "name" => "Fu Manchu",

    "creep_factor" => "Very High",

    "avg_growth_days" => 58



    You're probably wondering how the heck we display this info on the screen! Well, we first have to reference the parent array $moustaches, then the numerical value of the child array (Handlebar is [0], Salvador Dali [1], etc), and finally the custom key of the information we want to display (name, creep_factor, etc). It looks like this:

    <?php echo$moustaches[2][name]; ?>

    The above code will display Fu Manchu.

    - - -

    Important update regarding the "keys" in your arrays:

    After recording the last two lectures, and publishing my course, it came to my attention that I made a little mistake!

    I have a bad habit of not wrapping my keys in my associative & multidimensional arrays in quotations, or "strings".

    For example

    The incorrect way of coding associative arrays:

    $handlebar = array(
    		name => "Handlebar",
    		creep_factor => "High",
    		avg_growth_days => 14

    The correct way of coding associative arrays:

    $handlebar = array(
    		"name" => "Handlebar",
    		"creep_factor" => "High",
    		"avg_growth_days" => 14

    Some servers, like MAMP, might not report the error, and just assume the keys are wrapped in strings. Some servers are not as forgiving as MAMP on a Mac, very obviously letting you know you made an error.

    It's very important that your key names in your associative and multi-dimensional arrays are wrapped in quotation marks, single or double.

    No worries though! The course files have been updated (as of July 25, 2014), and you probably already have the updated files. For your reference, the exact folders that have been updated are:

    • 07_AssociativeArrays
    • 08_MultiDimensionalArrays
    • 09_GetYourHandsDirty
    • 26_Final/Instructor

    Thank you very much to everyone who pointed this out!




    Lecture 15: Get Your Hands Dirty

    In this lecture, we put together what we've learned so far about PHP Variables, Constants and Arrays!

    Section 4: PHP If, Else & Elseif

    Lecture 16: If Statements

    The point of coding in PHP is to make your website dynamic—or smart—so that it can make logical decisions. What I mean by this is your website can make decisions on what to do next based on user input, user conditions, or parameters you've set yourself. Here are some examples:

    • When a user logs into their account, they must type both their username and password. What if their password is wrong? What if they didn't type a valid email address? What if they forgot to type their email address altogether? PHP can handle what to do in these situations using If, Else, and Elseif statements.
    • What if a customer tries to buy a product online, but that product is sold out? PHP can let the user know the product is sold out because you can program it to calculate how many items of that product are remaining.
    • What if a user uploads an image that is too large? PHP can compare the uploaded image with your parameters and tell the user to upload a smaller image size if it exceeds the limit.
    • ...and so much more!

    Let's start with the If Statement. It works something like this:

    If THIS then THAT

    Okay, that was a little vague. Let's expand on that a bit:

    If expression is TRUE, then do something

    If expression is FALSE, then don't do anything

    What's an Expression?

    You're probably wondering what an "expression" is. Here's how explains what an expression is:

    Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value". The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).
    Back to If Statements

    Let's see what they look like in PHP:

    if (expression) {

    // code to execute if expression evaluates to TRUE


    If we expand on that further, it looks more like this:


    // Set some variables

    $a = 20;

    $b = 50;

    if ($a < $b) {

    echo "Yep! $a is certainly less than $b.";



    As you can see, we are using the "less than" symbol (<) to check if the variable $a is smaller than the variable $b. If the expression is TRUE, then PHP will echo the text "Yep! 20 is certainly less than 50."

    If statements can be very powerful, but these are just some very basic examples to get you started.


    Lecture 17: Else

    We've figured out how to execute some code if an expression evaluates to TRUE, but what about when the expression evaluates to FALSE? Often you'll want to execute some code if a certain condition has not been met.

    This is where Else comes in to play. Look at Else as an extension of the If statement. The syntax looks like this:

    if (expression) {

    // code to execute if TRUE

    } else {

    // code to execute if FALSE


    Now, let's take a look at a real-world example:


    $fav_fruit = "orange";

    if ($fav_fruit == "pineapple") {

    echo "YAY! Pineapple is the best.";

    } else {

    echo "So, you like oranges...";



    Not all "equals" are created equal

    It's good to remember that "==" is different than "=". The former means is equal to while the latter assigns a value to a variable. For example:

    if($fav_fruit= "pineapple")

    Will always evaluate to true because the single "=" symbol assigns the value into the variable, rather than comparing it.


    Lecture 18: Else if

    There's one last piece in the IF / ELSE puzzle. It's called ELSEIF (pronounced "Else If"). ELSEIF is a kind of combination of IF and ELSE. puts it nicely:

    Like ELSE, it extends an IF statement to execute a different statement in case the original IF expression evaluates to FALSE. However, unlike ELSE, it will execute that alternative expression only if the ELSEIF conditional expression evaluates to TRUE.

    If the above explanation is as clear as mud, the syntax looks like this:

    if (expression) {

    // code to execute if the above expression is TRUE

    } elseif (different expression) {

    /* code to execute if first expression is FALSE

    but the ELSEIF expression is TRUE */

    } else {

    /* code to execute if neither

    of the above expressions are TRUE */


    Now, if we added some real PHP, it would look like this:


    $native_language = "Spanish";

    if ($native_language == "French") {

    echo "Bonjour! Vouz parlez Français.";

    } elseif ($native_language == "Spanish") {

    echo "¡Hola! Usted habla Español.";

    } else {

    echo "Hello! You probably speak English.";



    Here's the commented code:


    // Setting the variable

    $native_language = "Spanish";

    // IF native language is French

    if ($native_language == "French") {

    // Echo some french!

    echo "Bonjour! Vouz parlez Français.";

    // ELSEIF native language is Spanish

    } elseif ($native_language == "Spanish") {

    // Echo some spanish!

    echo "¡Hola! Usted habla Español.";

    // ELSE native language is neither of the above

    } else {

    // Echo some english!

    echo "Hello! You probably speak English.";




    Lecture 19: Get Your Hands Dirty

    In this lecture, we're going to build a simple PHP script that utilizes the skills we've learned in this section: If Statements, Else and Elseif.

    Section 5: PHP Operators

    Lecture 20: Comparison Operators

    At this point, we've been playing with PHP Variables, Arrays, and If Statements. In nearly every lecture so far, we've seen the "=" symbol. You probably have a basic understanding that it sets a value to a variable, like so:

    $myName= "Brad";

    In the PHP world, the = symbol is called an "assignment operator". It basically "assigns" the value on the right to the variable on the left. There are many assignment operators, but we'll get into those once we've been introduced to the many other types of operators in PHP.

    First, we will start with the "comparison operator".

    Comparison operators allow you to compare multiple elements. You can compare whether elements are:

    • Equal
    • Exactly Equal (Identical)
    • Greater Than
    • Less Than
    • Plus a few more combinations of the above

    Here is a handy table, provided by

    Here is an example of how you would use one of the above comparison operators:

    $yearsOnEarth = 14;

    if ($yearsOnEarth <= 25) {

    echo "Your age is less than or equal to 25!";



    Lecture 21: Logical Operators

    Logical Operators are just that: logical! It's like speaking english. They are very helpful when you need your If / Else / Elseif statements to be a little more complex. Check out this table, provided by

    Here is an example of how you would use one of the above logical operators:

    $username = "johnnyboy";

    $password = "qwerty";

    if ($username == 'johnnyboy' && $password == 'qwerty') {

    // username and password are correct

    } else {

    echo "Your username and password combination are incorrect";



    Lecture 22: Arithmetic Operators

    This is where we start getting into some math! It's very basic, but incredibly useful. Check out this table, provided by

    The modulus operator is usually a pretty confusing concept at first, but provides a pretty good explanation here:

    The "mod" operator in computer languages is simply the remainder. For example,

    17 mod 3 = 2


    17 / 3 = 5 rem 2

    which in turn means

    17 = 3 * 5 + 2

    Here is an example of how you would use one of the above arithmetic operators:


    $birthYear = 1988;

    $thisYear = date('Y');

    $myAge = ($thisYear - 1988);

    echo $myAge;



    Lecture 23: String Operators

    This one's nice and simple: there are only two string operators. The first one is called the concatenation operator ".", which combines the value of the right argument with the left argument. Let's look at it like this:

    $a = "Hola ";

    $b = $a . "Mi Amigos!";

    echo $b; // This prints "Hola Mi Amigos!"

    The second operator is the concatenating assignment operator ".=", which appends the value in the right with the value in the left, like this:

    $a = "Hola ";

    $a .= "Mi Amigos!";

    echo $a; // This prints "Hola Mi Amigos!"

    The concatenating assignment operator is considered an "Assignment Operator" which we will be learning more about in the next lecture.


    Lecture 24: Assignment Operators

    Assignment Operators "assign" values from the right argument to the left argument — usually in the form of variables. The basic assignment operator is "=", which assigns the value on the right to the variable on the left. Here is a table of more assignment operators:

    Here's an example of how to use one of the above operators:


    $a = 71;

    $b = 36;

    $a -= $b;

    echo $a; // Prints 35


    Section 6: PHP Loops

    Lecture 25: While Loop

    When coding PHP, loops can be fantastic! Basically, you can write a piece of code to repeat itself again and again until a certain condition has been met. There are a few types of loops in PHP, in this lecture we'll learn about While Loops.

    Here's how a while loop works:

    while (condition is true) {

    // execute code


    At this point, you probably have no idea how to actually use a while loop in PHP. That's okay. Let's dive into how you actually use it.

    Let's say you want PHP to echo the numbers from 10 to 20. First you need to set a variable with your starting number:


    // Set a variable with your starting number

    $startingNum = 10;


    Then you need to start your while loop with a condition. In this case, we want our condition to say "while my starting number ($startingNum) is less than or equal to 20, the condition is true".

    To help clarify — as long as $startingNum is less than or equal to 20, keep on looping!


    // Set a variable with your starting number

    $startingNum = 10;

    // While $startingNum is less than or equal to 20

    while ($startingNum <= 20) {

    // execute code



    You may be thinking: "our starting number is 10, it will always be less than 20, dumbo!".

    Well, each time we loop through our function, we will tell PHP to increment our starting number by 1. Therefore, eventually our starting number will be equal to 20!

    Our condition says to stop looping once our starting number is larger than 20. We need to do this to prevent an infinite loop — something you most definitely don't want! An infinite loop means your function will literally run forever, which can freeze up your computer.

    So, let's tell PHP to echo our $startingNum variable, then increment the variable by 1:


    // Set a variable with your starting number

    $startingNum = 10;

    // While $startingNum is less than or equal to 20

    while ($startingNum <= 20) {

    // Echo the variable on the screen

    // We'll also concatenate a <br> tag at the end

    echo $startingNum . "<br>";

    // Then increment the value by 1




    In PHP, you can increment and decrement variables like so:
    $a++; adds 1 to the value of the variable $a each time through
    $a--; subtracts 1 from the value of the variable $a each time through

    If coded correctly, this code should echo the numbers 10 to 20 on your screen, and stop at 20. Keep in mind, you can use any of the operators we've used in our past lectures as the conditions that need to be met in the while loop.


    Lecture 26: For Loop

    For Loops are a little trickier to wrap your head around, so hang in there!

    The for loop is used when you know in advance how many times the script should run. — w3schools

    The syntax looks like so:

    for (initialize counter; test if TRUE; increment counter) {

    // execute code


    Essentially, the For Loop will:

    1. Initialize where the loop will start counting by adding a value to a variable
    2. Evaluate a certain condition to test if the condition is either TRUE or FALSE (if the condition is FALSE, the loop will stop running)
    3. Increment the value by 1 each time we loop through

    So, if we want to have our For Loop spit out the numbers 0 to 20, we would code the following:

    for ($a = 0; $a <= 20; $a++) {

    echo "Number: $a <br>";


    If coded correctly, this code should echo the numbers 0 to 20 on your screen, and stop at 20.


    Lecture 27: Foreach Loop

    The Foreach Loop! This loop is a very popular loop, and is used extensively in database-driven websites. The purpose of a Foreach Loop is to "loop through each key/value pair in an array" (w3schools).

    The syntax looks like so:

    foreach ($array as $value) {

    // execute code


    Basically, here's what happens during each loop iteration:

    1. Assign value of current array element to $value
    2. $value is echoed on the screen
    3. The array pointer then moves to the next element within the array
    4. Repeat from beginning until final array element

    Let's use a real-world example of how to use a Foreach Loop:

    // We need to create an array

    // Let's resurrect our array of moustaches

    $moustaches = array("Handlebar", "Salvador Dali", "Fu Manchu");

    // Loop through the $moustaches array

    foreach ($moustaches as $moustache) {

    // Output each individual value

    echo "I love the $moustache <br>";


    If coded correctly, this should echo the three moustaches in the array on your screen.


    Lecture 28: Do / While Loop

    The Do While Loop is a bit like the While Loop, but there's one major difference: the While Loop will only start if the condition is TRUE; whereas the Do While Loop will always execute the first time, and then evaluate whether the condition is TRUE afterwards.

    Here's what the syntax looks like:

    do {

    // execute code

    } while ( condition to be met );

    Let's look at a real example:

    // Set a variable

    $i = 1;

    do {

    // Do this code

    echo "Number: $i <br>";



    // Then evaluate this condition

    // Repeat loop if TRUE

    while ( $i <= 10 );

    If coded correctly, this should echo the numbers 1 to 10 on your screen.

    Section 7: PHP Functions

    Lecture 29: Intro to PHP Functions

    If you've made it this far, congratulations are in order! We've covered a lot of ground, and our PHP coding skills are becoming much more refined and skillful!

    I'm going to go ahead and say that functions are the Meat n' Potatoes (vegetarian version: Beans n' Rice) of most programming languages; they are fundamental when cooking a tasty PHP dinner!

    In PHP, there is a massive library (over 1000) of baked-in functions—pun intended—that do everything from printing text on your screen to adding information to a database, and much more!

    It's good to know that there are two types of PHP functions: Built-in PHP Functions, and Custom Functions (you can write your own custom PHP functions!).

    Remember echo and print? Those little guys are functions!

    Important Facts about Functions

    A function is a block of statements that can be used repeatedly in a program.

    A function will not execute immediately when a page loads.

    A function will be executed by a call to the function.


    Let's take a look at the basic syntax of a function:

    function functionName() {

    // execute code


    Please note: A function name can start with a letter or underscore (not a number). — w3schools

    Hot tip: You can name the function whatever you wish! Just try and have it reflect what the function actually does.

    PHP sort() Function

    Let's take a quick look at the built-in PHP sort() Function. This function allows us to sort an array in alphabetical order.

    First, let's create an array:

    // Custom array

    $dinner = array("Meat", "Potatoes", "Beans", "Rice");

    Now let's run our array through the sort() function:

    // Custom array

    $dinner = array("Meat", "Potatoes", "Beans", "Rice");

    // Add the array as a parameter to sort() function


    Now all we have to do is echo our array on the screen, using a Foreach loop:

    // Custom array

    $dinner = array("Meat", "Potatoes", "Beans", "Rice");

    // Add the array as a parameter to sort() function


    // Echo the sorted array

    foreach ($dinner as $ingredient) {

    echo "$ingredient <br>";


    If coded correctly, the above will echo the array in alphabetical order:


    If you're looking to sort your array in reverse order, you can use the PHP rsort()function. Feel free to read more about the sort function, and other sorting functions here.

    We won't be covering all of the built-in PHP functions in this course, because that would take an incredibly long time. Besides, it's fun to be in a situation where you're programming and then you think "Hey! I wonder if there's a PHP function that will do this for me?" — this is why I'll leave you with the curiosity to experiment. Google is your best friend, and you may also refer to this directory.


    Lecture 30: Custom Functions

    While PHP has a massive library of built-in functions you have at your disposal, sometimes you need to build your own functions — for both small and large tasks.

    Think of a custom functions as a mini-program that performs an action for you — better yet, think of a custom function as a cute little robot that does a specific task you tell it to do!

    Let's look at the basic syntax of a function:


    function myCustomFunction() {

    // things my custom function will do

    // go in here



    To build your custom function, you need to type function myCustomFunction(). Keep in mind that "myCustomFunction()" can be whatever words you want them to be, but no spaces allowed. Then add opening and closing curly brackets (or curly braces, as some call it). In between the curly brackets is where you define what your function will perform.

    There are two important things to know about functions:

    1. There are functions that require "arguments", and;
    2. There are functions that don't require "arguments".

    Let's start by building a custom function that does not require an argument.


    // Build the function

    function hangTen() {

    echo "Surf's up! Grab your board!";


    // Call the function




    Lecture 31: Simple Arguments

    Functions can be incredibly powerful, because you can program them to do almost anything you want them to. One important step in making your functions even smarter is to use "arguments" within your function. Not the type of argument where you and a friend are bickering about a disagreement, I'm talking about arguments within functions — two very different things.

    Think of an argument like a variable. Your program can pass extra information to your functions using arguments. You specify your arguments within the parenthesis after your function name, and you can have as many as you want, as long as they're comma separated.

    Let's look at an example of a function with a single argument:


    function hangTen($location) {

    echo "We're surfing in $location!<br>";






    So, in the above example, we're passing an argument to the hangTen() function. Later in our script, we call our function several times with a string of text within each parenthesis, and each time we call our function with a new argument value, that value will display on the screen along with the text we provided in our function.

    The output will look like this:

    We're surfing in Hawaii!
    We're surfing in California!
    We're surfing in Newfoundland!

    Let's look at an example with two arguments:


    function multiplyTogether($val1, $val2) {

    $product = $val1 * $val2;

    echo "The product of the two numbers is: $product";


    multiplyTogether(14, 27);


    All we did here was add another argument, separated by comma, then when we called our multiplyTogether() function later in the script, we provided two values to take the place of our $val1 and $val2 arguments.

    The result?

    The product of the two numbers is: 378

    Section 8: Coding a Dynamic PHP Restaurant Website

    Lecture 32: The Final Website

    In this lecture, we take a look at the final PHP website we'll be building based on the knowledge we've learned throughout this course.


    Lecture 33: Code a Basic Webpage Layout

    In this lecture, we code a standard HTML webpage.


    Lecture 34: Templating a Global Header & Footer

    In this lecture, we begin creating PHP header and footer templates. We also learn how to create a dynamic navigation menu using arrays.


    Lecture 35: Dynamic Copyright & Hours of Operation

    In this lecture, we learn how to create a dynamic copyright date, and also how to install a PHP plugin to let our users know if our store is currently open or closes.


    Lecture 36: Code a Team Member Array & Template

    In this lecture we code a PHP template that we use to display our team members.


    Lecture 37: Code a Menu Array & Template

    In this lecture, we build an array for our restaurant menu items, and build a template to display our menu items.


    Lecture 38: Understanding $_GET

    When the URL the browser requests includes a query string (anything after a question mark), the $_GET collection is created automatically. The string on the left side of an equals sign ( = ) becomes a variable name, and the thing on the right side of the equals sign becomes that variable's value.

    So, for example: in our previous lecture we have a link on our menu.php page that navigates to "dish.php?item=mexican-barbacoa". That URL will navigate to the dish.php template (which we have not created yet) and the $_GET collection will create a variable called "item" with the value of "mexican-barbacoa". We can then use that value to do something specific on our dish.php template.

    It could be as simple as "echo mexican-barbacoa" or, "display specific information in an array with the key of 'mexican-barbacoa'" This is what we will be doing in our next lecture.


    Lecture 39: Code a Menu Item Dynamic Template

    In this lecture, we code a PHP template that will allow us to populate the page with dynamic information based on the query string passed into the URL.


    Lecture 40: Code a Simple Contact Form

    In this lecture, we code a simple HTML contact form. In the upcoming lectures, we will learn how to submit the form, and perform simple validation on inputs.


    Lecture 41: Understanding $_POST

    In this lecture, we learn the basics of $_POST and how we will use it for PHP forms.


    Lecture 42: Simple Form Validation & Submission (Part 1)

    In this lecture, we start integrating PHP into our HTML contact form.


    Lecture 43: Simple Form Validation & Submission (Part 2)

    In this lecture, we continue from where we left off in Part 1.


    Lecture 44: Uploading our Website Live on the Web

    In this lecture, we learn how to get set up with some web hosting that supports PHP websites, and we upload our website live to a real web server.

    Required resource to upload live on the web:

    A Hosting Package (I recommend Justhost)


    Lecture 45: Wrap Up & Where To Go From Here

    Thanks for taking the course! I hope you've found value in it.

    This lecture gives you some next steps to take on your web development journey.



    Students Who Viewed This Course Also Viewed

    • Loading
    • Loading
    • Loading

    Instructor Biography

    Brad Hussey, Freelancing Web Designer @ Code College

    A highly skilled professional, Brad Hussey is a passionate and experienced freelancing web designer, developer, blogger and digital entrepreneur. Hailing from North Of The Wall (Yellowknife, Canada), Brad made the trek to the Wet Coast (Vancouver, Canada) to educate and equip himself with the necessary skills to become a spearhead in his trade of solving problems on the web, crafting design solutions, and speaking in code.

    Brad's determination and love for what he does has landed him in some pretty interesting places with some neat people. He's had the privilege of working with, and providing solutions for, numerous businesses, big & small, across the Americas.

    Brad builds custom websites, and provides design solutions for a wide-array of clientele at his company, Brightside Studios. He regularly blogs about passive income, living your life to the fullest, and provides premium quality web design tutorials and courses for tens of thousands of amazing people desiring to master the craft.

    180,000+ Students Don't Lie

    Join Brad and adventure into his world of web design, web development, and speaking in code. You won't regret it!

    What are people saying about Brad?

    "[Brad is] the BEST coding instructor on the planet. Brad has a passion for teaching and he does it with joy. He pours his heart into his lessons and makes you feel at ease. It's just like having your best buddy having a chat with you - only this time, you are learning valuable skills. He's the type of guy who is passionate about transforming people's lives through his lessons. He's not after the money. He truly wants you to succeed.Three hearty cheers to Brad - the best coding instructor on planet Earth."

    — Cicero, Brad's student

    "...These videos are well created, concise, fast-paced, easy to follow, and just funny enough to keep you chuckling as you're slamming out lines of code. I've taken 3 courses from this instructor. Whenever I have questions he is right there with a simple solution or a helpful suggestion to keep me going forward with the course work."

    — Brennan, Brad's student

    "...Brad is amazing and I honestly think he's the best tutor of all the courses I have taken on Udemy. Will definitely be following him in the future. Thanks Brad!"

    — Brad's student

    "...Brad has an infectious enthusiasm, a great eye for detail, and expert-level knowledge of the material."

    — Brad's student

    Instructor Biography

    Code College, The Best Coding Courses on the Web

    Code College is an online school that provides high quality learning material, courses, and training videos for students looking to learn web design, web development, marketing, online business, and more!

    Founded in 2014 by Canadian entrepreneur, successful instructor, and blogger, Brad Hussey, Code College is a growing network of highly skilled instructors who provide the best quality tutorials, courses and learning material on the web.

    Ready to start learning?
    Start Learning Now