
Lecture Description
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:
Assign value of current array element to $value
$value is 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 array
foreach ($moustaches as $moustache) {
// Output each individual value
echo "I love the $moustache. ";
}
If coded correctly, this should echo the three moustaches in the array on your screen.
DOWNLOAD COURSE FILES HERE
www.bradhussey.ca/download-php-course
Course Index
- Welcome to the Course
- What is PHP?
- What Does PHP Do?
- Tools to Get Started
- Download Course Files
- Your First PHP Page
- PHP Syntax
- PHP Variables
- More Variables
- Defining Constants
- Get Your Hands Dirty
- Arrays
- Associative Arrays
- Multi-Dimensional Arrays
- Get Your Hands Dirty
- If Statements
- Else
- Else If
- Get Your Hands Dirty
- Comparison Operators
- Logical Operators
- Arithmetic Operators
- String Operators
- Assignment Operators
- While Loop
- For Loop
- Foreach Loop
- Do While Loop
- PHP Functions
- Custom Functions
- Simple Arguments
- Final Website
- Basic Layout
- Global Header & Footer
- Copyright & Hours of Operation
- Team Member Array & Template
- Menu Array & Template
- Understanding $_GET
- Menu Item Template
- Contact Form
- Understanding $_POST
- Form Validation
- Form Submission
- Upload Your Website Live
- Wrap Up
Course Description
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).
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.