Practical PHP: Master the Basics and Code Dynamic Websites
- Description
- Curriculum
- FAQ
- Reviews
Learn How to Code Dynamic Websites with PHP 5+ 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:
- I don’t want a purchasing decision to get in the way of you learning what I have to offer in this course.
- I want as many people as possible to be able access the content.
- 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.
-
1Welcome!Video lesson
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:
- I don't want a purchasing decision to get in the way of you learning what I have to offer in this course.
- I want as many people as possible to be able access the content.
- 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.
-
2What is PHP?Video lesson
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 PHP.net 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!
-
3What does PHP do?Video lesson
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!
-
4Tools to Get StartedVideo lesson
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
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.
Browsers
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 bradhussey.ca/resources 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.
-
5The Course FilesVideo lesson
Lecture 5: The Course Files
You may download the course files, absolutely free, using the following link:
-
6PHP Pop Quiz!Quiz
Testing your short-term memory.
-
7Your First PHP Web PageVideo lesson
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!
-
8PHP SyntaxVideo lesson
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.
-
9PHP VariablesVideo lesson
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.
-
10More VariablesVideo lesson
Lecture 9: More Variables
In this lecture, we cover a couple more examples of the basic usage of PHP variables.
-
11Defining ConstantsVideo lesson
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:
<?phpechoTITLE; ?> -
12Get Your Hands Dirty!Video lesson
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!
-
13PHP ArraysVideo lesson
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:
<?phpecho$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!
-
14PHP Associative ArraysVideo lesson
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:
<?phpecho$handlebar[creep_factor]; ?> -
15PHP Multi-Dimensional ArraysVideo lesson
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:<?phpecho$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!
Cheers,
Brad
-
16Get Your Hands Dirty!Video lesson
Lecture 15: Get Your Hands Dirty
In this lecture, we put together what we've learned so far about PHP Variables, Constants and Arrays!
-
17If StatementsVideo lesson
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 THATOkay, that was a little vague. Let's expand on that a bit:
If expression is TRUE, thendosomethingIf expression is FALSE, then don'tdoanythingWhat's an Expression?
You're probably wondering what an "expression" is. Here's how PHP.net 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:
<?php// 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$ais smaller than the variable$b. If the expression isTRUE, 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.
-
18PHP ElseVideo lesson
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 toFALSE? Often you'll want to execute some code if a certain condition has not been met.This is where
Elsecomes in to play. Look atElseas an extension of theIfstatement. 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:
<?php$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. -
19PHP ElseifVideo lesson
Lecture 18: Else if
There's one last piece in the
IF / ELSEpuzzle. It's calledELSEIF(pronounced "Else If").ELSEIFis a kind of combination ofIFandELSE. PHP.net puts it nicely:
LikeELSE, it extends anIFstatement to execute a different statement in case the originalIFexpression evaluates toFALSE. However, unlikeELSE, it will execute that alternative expression only if theELSEIFconditional expression evaluates toTRUE.
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 FALSEbut the ELSEIF expression is TRUE */}else{/* code to execute if neitherof the above expressions are TRUE */}Now, if we added some real PHP, it would look like this:
<?php$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:
<?php// Setting the variable$native_language="Spanish";// IF native language is Frenchif($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.";}?> -
20Get Your Hands Dirty!Video lesson
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.
-
21Comparison OperatorsVideo lesson
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 PHP.net
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!";}
-
22Logical OperatorsVideo lesson
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 / Elseifstatements to be a little more complex. Check out this table, provided by PHP.net:
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";} -
23Arithmetic OperatorsVideo lesson
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 PHP.net:
The modulus operator is usually a pretty confusing concept at first, but mathforum.org provides a pretty good explanation here:
The "mod" operator in computer languages is simply the remainder. For example,
17 mod 3 = 2because
17 / 3 = 5 rem 2which in turn means
17 = 3 * 5 + 2Here is an example of how you would use one of the above arithmetic operators:
<?php$birthYear= 1988;$thisYear=date('Y');$myAge= ($thisYear- 1988);echo$myAge;?> -
24String OperatorsVideo lesson
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.
-
25Assignment OperatorsVideo lesson
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:
<?php$a= 71;$b= 36;$a-=$b;echo$a;// Prints 35?>
-
26While LoopVideo lesson
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:
<?php// 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
$startingNumis less than or equal to 20, keep on looping!<?php// Set a variable with your starting number$startingNum= 10;// While $startingNum is less than or equal to 20while($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
$startingNumvariable, then increment the variable by 1:<?php// Set a variable with your starting number$startingNum= 10;// While $startingNum is less than or equal to 20while($startingNum<= 20) {// Echo the variable on the screen// We'll also concatenate a <br> tag at the endecho$startingNum."<br>";// Then increment the value by 1$startingNum++;}?>In PHP, you can increment and decrement variables like so:
$a++;adds 1 to the value of the variable $aeach time through$a--;subtracts 1 from the value of the variable $aeach time throughIf 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.
-
27For LoopVideo lesson
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; testifTRUE; increment counter) {// execute code}Essentially, the For Loop will:
- Initialize where the loop will start counting by adding a value to a variable
- Evaluate a certain condition to test if the condition is either TRUE or FALSE (if the condition is FALSE, the loop will stop running)
- 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.
-
28Foreach LoopVideo lesson
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($arrayas$value) {// execute code}Basically, here's what happens during each loop iteration:
- Assign value of current array element to
$value $valueis echoed on the screen- The array pointer then moves to the next element within the array
- 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 arrayforeach($moustachesas$moustache) {// Output each individual valueecho"I love the $moustache <br>";}If coded correctly, this should echo the three moustaches in the array on your screen.
- Assign value of current array element to
-
29Do / While LoopVideo lesson
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 codeecho"Number: $i <br>";$i++;}// Then evaluate this condition// Repeat loop if TRUEwhile($i<= 10 );If coded correctly, this should echo the numbers 1 to 10 on your screen.
-
30Intro to PHP FunctionsVideo lesson
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
echoandprint? 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:
functionfunctionName() {// 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()FunctionLet'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() functionsort($dinner);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() functionsort($dinner);// Echo the sorted arrayforeach($dinneras$ingredient) {echo"$ingredient <br>";}If coded correctly, the above will echo the array in alphabetical order:
Beans
Meat
Potatoes
RiceIf 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.
-
31Custom FunctionsVideo lesson
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:
<?phpfunctionmyCustomFunction() {// 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:
- There are functions that require "arguments", and;
- There are functions that don't require "arguments".
Let's start by building a custom function that does not require an argument.
<?php// Build the functionfunctionhangTen() {echo"Surf's up! Grab your board!";}// Call the functionhangTen();?> -
32Simple ArgumentsVideo lesson
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:
<?phpfunctionhangTen($location) {echo"We're surfing in $location!<br>";}hangTen("Hawaii");hangTen("California");hangTen("Newfoundland");?>
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:
<?phpfunctionmultiplyTogether($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$val1and$val2arguments.The result?
The product of the two numbers is: 378
External Links May Contain Affiliate Links read more