Enter your Sign on user name and password.

Forgot password?
  • Follow us on:
Loading video...

Start Learning Now

Our free lessons will get you started (Flash® 10 required).
Get immediate access to our entire library.

Sign up for Educator.com

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

For & Foreach Loops

  • A for loop is a type of conditional loop that requires three expressions in its definition:
    • the 1st expression is evaluated once and only once before the loop begins iteration
    • the 2nd expression is the test condition for the loop, whose value is compared to TRUE before each iteration
    • the 3rd expression gets evaluated after each iteration of the loop
  • A foreach loop is a special type of conditional loop used specifically for iterating over arrays. When using a foreach loop to iterate over an array, the array’s internal cursor is automatically reset by PHP before entering the loop and automatically advanced by one on each loop iteration.
  • foreach loops have two syntaxes. One is typically used for iterating over indexed arrays and the other for iterating over associative arrays.
  • Both continue and break statements work within for and foreach loops just as they do in while and do-while loops.
  • Additional Resources:

For & Foreach Loops

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

Computer Science: Introduction to PHP

Transcription: For & Foreach Loops

Hello again, and welcome back to Educator.com's Introduction to PHP course.0000

In today's lesson, we are going to be introducing two new conditional loops that PHP provides: the for loop and the foreach loop.0004

We are going to be talking specifically about the for loops and what they are: they are similar, in a way, to a while loop.0012

We are going to be talking about foreach loops, which are specifically meant for looping or iterating over arrays,0018

which is an extremely common task in PHP code.0023

And then, foreach loops have two different syntaxes, typically depending on whether you are iterating over a numerically indexed array or an associative array.0027

We are going to go over both of those syntaxes, and then we are going to go over the coding conventions0037

that we are going to use in this course for the for and foreach loops.0040

As mentioned, a for loop is a new kind of loop we are going to introduce.0046

It is a conditional loop that works kind of like a while loop, except it is a little more complex.0050

It has three expressions that it uses to declare it; and this is an example of a for loop.0055

It has the for keyword, and then it has three expressions, separated by semicolons (and we are going to explain in a second what those all do).0062

And just as a while loop does, it has a statement group enclosed in curly braces.0070

And every time you loop over the for loop, you execute the statements in the statement group.0075

This expression here, expr1, is an expression that you evaluate once before the loop starts.0083

So, when you are (let me erase this) in whatever line of code is before this for loop, when that is done executing0089

(for example, you have a statement), and you begin to execute this for loop, expr1 gets evaluated: it always gets evaluated one time.0098

Then, what happens is: you have expr2, which is your test expression, which is just like the test expression in the while loop.0107

If that test expression is true, then you go ahead and execute the statements in your statement group.0115

Then, expr3 is an expression that is evaluated or executed at the end of each and every loop.0121

So, every time you have a test expression that is true, you execute the statements in the loop.0129

Then, you go ahead and evaluate expr3, which is typically something like incrementing a counter.0134

You re-evaluate the test expression, expr2; and if it is still true, then you go ahead and loop through it again.0140

This is a simple example of a for loop that is going to output the string of numbers "1, 2, 3, 4, 5."0148

And so, for your first expression here, we have a variable declaration, i, and we are setting it equal to 1.0156

So, when whatever statement is up here is done executing, and this for loop begins, the first thing it does is executes the statement.0163

What it executes: it creates a variable i, or if it is already created, it sets the variable i equal to 1.0170

Then, it evaluates this test condition, which is the second expression in a for loop.0176

It is going to say, "Is the value of i less than or equal to 5?"0183

Well, we just set it equal to 1, so that is going to evaluate to true.0186

Because that is true, it is going to execute the statement group, which, in this case, is just an echo statement.0189

And all it is going to do is echo the value of i.0196

Once it echoes the value of i (it is going to echo the first value, 1, here), then, because the loop has ended, it goes and evaluates expr3.0199

expr3, in this case, is an increment operation on the variable i.0211

So now, i that was previously 1...after the loop goes through a first time, i is now equal to 2; and that is on the second iteration.0216

One thing to note, importantly, is that this only gets executed when the loop first begins; it doesn't get executed on each loop.0226

So now, i is equal to 2 (let me clean this up here a little bit); it is going to evaluate the test expression again.0234

2 is less than or equal to 5; it is going to echo it out.0245

Again, it is going to increment i; i is going to be equal to 3; 3 is less than 5; it is going to echo it out.0248

It does so until i equals 5; then, when i equals 5, it is going to echo it.0253

So, we are going to have this string echoed; it is going to increment i a fifth time.0259

i is going to be equal to 6 now; then, when it goes ahead and evaluates this expression, 6 is not less than or equal to 5; it returns false.0265

The loop exits, and you jump out to whatever code was down here.0275

Now, this may look kind of familiar, because it is sort of the same structure that we used when we used a while loop with a counter.0278

And this same exact for loop could be written in a while loop, as well.0285

For example, let's say this was in a different script: we could declare a counter, like we have done before; we'll declare a counter i=0.0292

Then, we are going to create a while loop; and in our while loop, we are going to set the expression i less than or equal to 5.0302

Opening curly brace...echo i...and then, after we echo i, as we have seen in other while loops that we have used, we want to increment the counter.0313

So, we are going to increment i and close the curly brace; and this code here (actually, I made a mistake here;0328

this should be 1)--this while loop right here performs the same exact functionality as this for loop up here.0335

The for loop is a little bit cleaner; you don't have to include these increment statements within your while loop.0344

You don't have to include the declaration statement before the while loop.0349

So, when you are using these examples where you are going to be using counter variables, it is usually preferable to use the for loop,0352

because you can initialize your variable, create the test condition, and then also increment your counter, all on one line,0360

rather than, as here, in 1, 2, 3 different spots.0369

And so, again, this while loop is the same functionality.0373

Now, one important thing to notice is the semicolons here: you have to separate the first expression from the second expression 0377

with a semicolon, as well as the second expression from the third expression with a semicolon.0385

And that is key: otherwise, you will get a syntax error, or a partial error, when you try to run your code.0390

Let's take a look at a for loop in a more practical application, looking at iterating over an array.0396

We have an example file called forLoops.php, and we are going to iterate over an indexed array.0402

And what you can see is: we have declared an indexed array here with just three strings in it: the characters a, b, and c, all in lowercase.0414

Now, what we have done here is: we have created a for loop, and we have created an initial counter, set equal to 0.0422

We have created our test condition that, as long as i is less than the count (or the size of the indexed array), the loop is going to continue to iterate.0428

And then, we are also going to increment i at the end of each loop.0437

So, what this is going to do is: it is going to loop over the indexed array.0440

It is going to start at element 0, and then it is going to increment i after each iteration, until it gets to 5.0444

Once it is equal to 5, it is not going to be less than the count anymore; you are going to jump out of the loop.0452

And then, all we are doing, simply, within the loop, is: we have a simple echo statement that is outputting a statement that says,0456

"The element of indexArr at this index here (we are just going to use i as the index, so the first time through, it's 0,0462

because as we know, indexed arrays start with a 0 index)...it's going to say indexArr[0] in Uppercase."0474

And then, we are going to access that value in the indexed array.0481

In the first iteration of the loop, we are going to access the 0 element of the array; I'm going to output it as uppercase.0487

What this is going to do is: this loop is going to be iterating over an array, and in this case, 0494

it is going to be making uppercase versions of the letters in it and outputting it.0501

And so, this is an example of using a loop to iterate over an array to perform some functions on the elements in it.0505

If we go and run this code, we can see that it says indexArr[0] in uppercase is A; 1 is uppercase B; 2 is uppercase C.0511

And we have this statement here, "ending loop using the test condition."0524

And we are going to come back to that in a second; but what that is saying is that this loop ends because the test condition eventually returned false.0527

And speaking to that matter about the test condition, as we know, there are while loops and do-while loops.0539

You can use break statements to break out of loops, as well.0544

So, both the continue and the break statement work within four loops, exactly as they do as while or do-while loops.0547

A continue statement will have you jump back up to the beginning of the loop and evaluate the test condition again.0555

When continue works with a for loop, though, it also (because it reaches the end of the loop) is going to evaluate that third expression, as well.0563

So, that counter will get incremented.0570

The break statement just jumps out of the loop, just as it did with the while loop.0572

And then, additionally, like in our while statements, sometimes when we use break conditions, 0577

you would have an indefinite loop by declaring while equal to true.0582

And then, somewhere within our loop statement group, we would have a break statement that would allow us to jump out of the loop.0588

We can do that similarly--create an indefinite loop in a for loop--by leaving the second expression in the for loop definition blank.0594

But you have to include its semicolon; so let's take a look at what that looks like.0604

Down here (let me just un-comment the code), as you can see, we have a for loop definition.0610

We have a counter variable that we have set equal to i; we have our increment operation, which occurs at the end of each iteration of the loop.0619

And here, as you can see, we have left the second expression, which is the test condition, blank.0628

And when you do that in PHP, that is essentially saying the test condition is equal to true, 0633

which means that loop is going to run indefinitely until it encounters a break statement.0637

Notice that we have included the second semicolon here, even though there is nothing here.0642

And if you left that out, you would get an error; so we are going to leave that in there.0646

And then, just for demonstration purposes, all we have done, essentially, is move that test condition into the loop.0650

And whereas before, we were saying, "If i is less than count index..." now we are saying, "If i is greater than or equal to the count index,0656

then the end of the array has been reached; go ahead and break."0664

And as we know how break works...it works the same as in a while loop.0667

Once the statement is reached, it automatically jumps out of the loop, and we come down here and execute whatever next statement is available.0670

If i is not greater than or equal to the count of the array, it is going to perform the same echo operation that we did up here.0678

It is going to output and say, "Indexed array, element 0, equals the uppercase version of that."0685

So, if we go and run this (make sure it's saved; refresh the page), now we can see here: ending the loop using the break statement,0691

it performs the same exact function, except we have used a break statement.0702

And again, the reasoning behind doing this example is to show you how to do an indefinite loop using a for loop,0707

and then also to show you how that the break statement still works within for loops, as well.0715

Now, the next kind of loop that we are going to talk about is probably the one used most often in PHP; it is called a foreach loop.0724

And it is a special type of loop, similar to the for loop, similar to the while loop, but it is made specifically for iterating over arrays,0730

which is a very common function that you do in PHP--actually, in all programming languages.0737

So, it is built into the PHP itself.0744

What it does (and I am going to show you the syntax in a second) is: you provide the foreach loop with an array that you want to iterate over.0749

What it does is: when that foreach loop starts, it sets the array's cursor.0758

Again, the array cursor, the internal array pointer, is where the current element of the array is right now.0763

We saw, in our previous lessons on while loops, how you could move the array cursor by using the next function, or previous,0771

or using the reset function to set it back to the beginning.0777

When you enter a foreach loop, it automatically resets the cursor back to the first element.0781

It calls the each function on the array, which is going to pull out the key and value for you, if you need those.0785

And then, as the each function works, it increments the array cursor one.0794

It is going to go ahead and execute the statements in the foreach loop.0798

And then, because the array cursor has been executed, when it gets back to the beginning of the loop,0802

it is going to pull out the key and value of the next item.0808

It is going to advance the array cursor by one and repeat.0810

Now, as we know from the each function, eventually, when the each function gets to an array where the cursor is past the last element,0813

it returns false, and then that is how the loop breaks out of the loop.0821

That is with a for loop and all of our other loops; continue and break statements work exactly the same.0825

And a foreach loop comes in two syntaxes.0831

They both can be used for indexed arrays and associative arrays, but typically one is used for iterating over indexed arrays.0835

And so, we are just going to call it the indexed array syntax.0841

And likewise, there is one that is used typically for iterating over associative arrays, so we are going to call that the associative array syntax.0844

This is what a foreach loop for indexed array syntax looks like.0853

We have the foreach keyword, and then here, we have a parentheses.0857

And what we do is we supply it (in this case, it would be) an array--a variable that is an array.0862

Then, you have a special keyword here called as; and then, we define a variable, and we can call it whatever we want here.0869

In this case, we are calling it value.0877

What that means is: first, when the loop begins, it resets the array cursor in array to the first element.0878

It is going to pull the value of that first element, and set whatever variable we declared here equal to that value.0888

It is going to run the statement group (for example, we could say echo 'value').0895

Now, every time it pulls that value out of the array, it is running the each function, so it is going to advance the array cursor.0903

So, the next time, when it loops back up here, it is going to go to the second item in the array.0913

It is going to set the variable ('value' again) to whatever the value of the next element in the array is.0917

Here is a more concrete example: we define an array called indexArr, which just has three numbers (1, 2, and 3) in it.0924

And then, here is an example of using the foreach statement to loop over that array; and we are going to output each of the values in the array.0932

This first argument (or expression, you might call it) that you provide to the foreach loop is the array you want to iterate over.0939

So, in this case, we want to iterate over the indexArr.0946

We have the as keyword, and then, when we iterate over, we are creating a variable called value 0948

that we are going to have foreach populate with whatever the value of the current array element is at that time.0955

So, when this foreach loop begins, the first thing it does is resets the array cursor indexArr to the first element; so it's going to be pointing at 1.0963

It sets value equal to 1; it enters and advances the array cursor (so the array cursor, at this point, is pointing to 2).0971

It goes ahead and runs a statement group (and in this case, we are just basically echoing the value that was set).0980

It returns back to the top, and it is going to, again, set value equal to the value of the current element in the array.0985

Since the array cursor was advanced, value is then going to be set to 2.0994

It is going to set value to 2; it is going to echo 2; it is going to repeat again to 3.0998

When it comes around the fourth time, the array cursor will have advanced past the end,1003

so that each function that it is implicitly calling is going to return false.1006

And then, it is going to jump out of the loop.1011

Let's take a look at another example of a foreach loop looping over an indexed array.1015

We have an indexed array that contains the same values that we had in the previous example for for loops--just the lowercase letters a, b, and c.1023

We are going to use the foreach loop to iterate over that array and just output, as we did before, 1033

the uppercase values of each of the elements in that indexed array.1039

So, here we provide with the name of the array we want to iterate over, indexArr.1045

We provide the name of the variable that we want to access the current array element's value as.1052

And in this case, we want to access, within our statement group, the current element's value with the variable called value.1063

What it is going to do is: when this first occurs, it is going to reset the cursor of indexArr to the first element, to point to a.1071

It is going to set value equal to a; it is going to advance the cursor; it is going to run the statement group, because value is now set to a.1078

It is going to run the strtoupper function, and it is going to output that.1085

And it is going to repeat that for each element in that array.1089

If we go and look at this script and how it runs, we can just see what it does.1094

Looping over the indexed array, it output all of the values in uppercase.1102

The other syntax that you can use with a foreach loop is typically used for associative arrays.1112

It pretty much looks exactly the same as the other one, except for this part right here.1118

The indexed array syntax of the foreach loop would set this last variable that you provide 1125

to the value of the current element in the array that you are looping over.1136

In this one, you can additionally not only extract the value into whatever variable you want to call it (here, we are calling it 'value'),1143

but you also can extract the key of the current element in the array.1150

So again, when we enter the foreach loop, whatever array we pass it, it is going to set the array cursor to the first element in the array.1157

It is going to set key equal to the key of that first element; it is going to set value equal to the value of that first element.1165

It is going to advance the array cursor; it is going to execute the statement group.1171

Maybe we will be making use of these variables.1175

It is going to come back up to iterate the loop again; as long as there is another element in the array to iterate over,1179

it is going to continue to do that until it reaches the end of the array.1184

Here is a concrete example: we have an array called assocArr that has two key/value pairs in it.1187

One key is called first, which we have set to the string 'joe'; one key is called last, which we have set to 'smith' to represent a first and last name.1195

And what we are going to do is just iterate over that associative array and output all of those key/value pairs.1202

What we have done is provided assocArr to the foreach loop, which is the array we are going to loop over.1209

And then, we are saying that, for every element of assocArr that gets looped over, we want the key of the current element1215

being looped over--the variable key--to be set to the value of the key of the current element.1224

We want this variable value to be set to the value of the current element that is being iterated over.1232

Then, here, we have a simple echo statement that is just outputting the current key with our array operator.1240

And then...it doesn't actually operate it; this is just a string being output so that we can see it.1250

And then, it is going to output the value.1255

When you run this array, it is going to output two lines.1258

The first one is going to say first, and then with this array operator as a string, 'joe'.1261

And then, the second line is going to say last='smith'.1268

Let's take a look at iterating over an associative array now, using this other syntax for foreach.1274

Here, we have an associative array that contains three key/value pairs--three elements.1285

The key to each of the three elements is a three-letter abbreviation for the month, for the first three months.1291

The value associated with those abbreviated month keys is the full name of the month, all spelled out.1298

We are going to do the same thing we just saw in the last example: we are going to loop over that associative array, using a foreach loop.1306

And we are just going to output all of the key/value pairs that we find.1312

So, when this foreach loop starts, assocArr's cursor gets reset to this first element, which is jan=January.1316

It is going to set key equal to the value jan, which is the key of the current element.1324

It is going to set value equal to the string 'January', which is the value of the current element, and advance the array cursor.1330

Then, it is going to go ahead and process the statement group that is associated with the loop.1336

Here, we are just outputting the key and the value.1341

It is going to come back up to the loop again, as long as there is another element in the array (which there is).1345

Then, it is going to set key equal to feb; it is going to set value equal to February.1349

It is going to run that again; it is going to do that for all three of these key/value pairs within the associative array.1354

And so, when we run this, we should see an output of all of those.1359

So, let's take a look at what this looks like in the browser.1362

And here, you can see, looping over the associative array, it does what we expect: 1367

it output the key, which gets set as that key variable that we defined in the parentheses of the foreach loop.1370

And then, it outputs the value of the current array element that it is looping over.1379

And this value variable was set to that value.1383

Now, one thing to note is that, even though this is an associative array syntax, it actually can be used for indexed arrays, too,1392

because indexed arrays have keys; they are just not strings--they are actually numbers.1399

Let's say, for example, we just removed the keys of this array so it becomes an indexed array.1403

Now, each of these values (January, February, and March)--they all have an index.1417

But the index is a numeric index, so it is going to be 0, 1, and 2.1422

So, you can still use this: when we output it, it is going to say, "0=January; 1=February; 2=March."1425

And so, if we go ahead and refresh the page, we can see that that is exactly what it has done.1432

So, you can use that syntax for indexed arrays, as well.1437

Likewise, you can use the (actually, let me undo this) indexed array syntax 1443

for looping over an associative array, as well, if you are only interested in the value.1465

So, for example, we have an associative array here, which is the same as before, with our abbreviated months and then their full names.1469

And when you loop over it in this way, it is just going to pull the value out; so all it is going to pull is January, February, March.1476

And so, we can just go ahead and output each of those values when it loops over it, and it is just going to pull the values out.1482

When we run this, it is just going to say "January, February, March," which it does.1488

You can use either syntax; typically, the indexed array syntax, as we call it, is used to iterate over indexed arrays,1492

And the associative array syntax is used to iterate over associative arrays.1500

Coding conventions for for loops and foreach loops: for loops are going to be formatted like this, similar to the syntax we have been using before.1506

We have the keyword followed by a space, and then the parentheses for the expressions (in this case) of the for loop,1515

followed by a space, and then the opening curly brace on the same line.1523

You are going to have the closing curly brace at the same indentation as the for keyword.1527

All of the statements within the statement group are going to be indented one indent.1532

And then, for the for loop, because we have three expressions, we are going to have each expression...1536

The first two will be immediately followed by a semicolon and a space, 1541

so we have a semicolon and a space, as opposed to just having a semicolon and no space here.1545

So, we are always going to do that: the space is not necessary, but that is going to be the convention.1553

That is our convention for for loops; for our foreach loops, they are going to be formatted as this.1557

It is the same thing as with a for loop: we have a space between the parentheses and the foreach keyword,1562

space here, curly brace in the same line, closing curly brace indented the same, statement indented one...1567

And then, what we have is: immediately following the opening parentheses, we list our array variable, followed by a space 1574

and the as keyword, followed by another space, and then the name of the variable that we are going to be setting the value to.1581

The foreach in the associative array syntax is going to be basically exactly the same, 1589

except that we are going to add this key and this array assignment operator sign.1595

There is still going to be a space between as and whatever variable we decide to set for key, 1601

a space between key and the array assignment operator, and a space between the array assignment operator and value.1605

That is the syntax we are going to use for that.1611

For the homework challenge, I want you to create an empty indexed array called numbers.1615

You are going to use a for loop; instead of iterating over an array, in this case, we are going to be populating an array.1619

And I want you to use the for loop to populate this indexed array, numbers, with the integers 1 through 5.1625

And the hint here is to use the value of the loop's counter variable as a way to populate numbers.1633

At the end of this first for loop, numbers should be an indexed array containing the numbers 1, 2, 3, 4, and 5.1640

Then, I want you to use a foreach loop to iterate over that array, the now-populated numbers.1647

And what I want you to do is iterate over the array, adding up each of the numbers in the array.1652

So, by the end, you should have a sum that equals 15, because 1, 2, 3, 4, and 5 added together equals 15.1658

So, after you iterate over the array, you want to output the sum (this variable sum that I am going to have you create).1665

And then, verify that it equals 15.1672

And then, one other thing that I want you to do is create a separate foreach loop.1675

And I am going to have you iterate over the GET superglobal, which, as we know, 1680

is the array that holds all of our GET name/value pairs that are supplied to a script.1684

And on each iteration over the GET array, I just want you to output the name and value of each GET variable.1689

Now, in a script that has no name/value pairs passed to it, nothing is going to happen.1697

But what I would like you to do is then generate some random name/value pairs, and append them as query strings1703

to whatever your script is, so that when you supply them to them, when this loop runs, it is going to output each of those name/value pairs.1711

And what you should do is supply some random name/value pairs, like first='joe' & last='smith'.1718

Provide that as a query string to whatever your script name is, and then verify that when you run that, you get output:1733

first is 'joe' (or maybe you want to use that symbol); last equals 'smith'.1741

And try that for any number of different variables; that will give you an example of iterating over the GET array, which is something that is often done.1754

That ends today's lesson; thank you for watching Educator.com--I look forward to seeing you next time.1763