Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Bookmark and Share

Start Learning Now

Our free lessons will get you started (Adobe Flash® 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!

Nested Conditional Control Structures

  • PHP allows the nesting of control structures, which means the statement group of one conditional control structure can contain other conditional control structures.
  • There is no limit to the number of levels of nesting allowed.
  • Common control structure errors include:
    • Incorrectly specified test conditions
    • Forgetting a break statement
    • Incorrectly placing an opening or closing curly brace

Nested Conditional Control Structures

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.

  • Intro 0:00
  • Lesson Overview 0:10
    • Lesson Overview
  • Nested Control Structures 0:36
    • Nested Control Structures
    • Nested Control Structures Coding Example
  • Coding Conventions 6:34
    • Nested vs. Not Nested Control Structures
  • Debugging Control Structures 7:51
    • Debugging Control Structures
    • Incorrectly Specified Test Conditions and Forgetting a Break Statement
    • Incorrectly Placing an Opening or Closing Curly Brace
  • Debugging Tips 16:24
    • Tracing the Execution of Your Code
    • Adding Echo Statement
  • Homework Challenge 21:41
    • Homework Challenge
  • Homework Challenge (cont.) 23:08
    • Homework Challenge (cont.)

Transcription: Nested Conditional Control Structures

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

In today's lesson, we are going to be covering the topic of nested conditional control structures.0005

Specifically, we are going to be learning about what a nested conditional control structure is and how to use it.0012

We are going to talk about coding conventions as they apply to nested control structures.0018

And then, we are also going to go over how to debug conditional control structures:0023

especially once nested gets involved, as you will see, they can become quite complicated.0030

So, we are going to provide some debugging tips for you.0035

Nesting control structures means that, within the statement group of one conditional control structure, you include another conditional control structure.0039

For example, if we have an if statement with its test condition, and then its opening brace,0049

these opening and closing braces define the statement group of that if statement.0056

Well, within this if statement, we have included another conditional control structure--another if statement.0061

And then, within this if statement, we have included another conditional control structure, this statement.0069

These actually should be indented one further.0077

And so, what you can see is that, in PHP, there is no limit to the number of levels--how deep you can nest control structures.0081

And what it allows you to do is to achieve fine-grain control over the execution of conditional segments of your code.0090

For example, maybe you have a section of code that you want to run if someone is a female, their age is over 25, and they are over 60" tall.0100

In this case, the code we would execute would be "you are a female over age 25, over 5 feet tall."0109

Using nested control structures like this allows you to achieve that sort of fine-grain control, 0116

to only execute code based on if multiple conditions are met.0123

Let's go and take a look at a script I have created called nested.php.0129

And what it does...before I get into this stuff here at the top, let's look at the code for it.0135

It takes two GET parameters: one called function and one called arg.0140

function can take on one of three different values: date, toUpper, or toLower.0149

What that is going to correspond to is the date function, the strtoupper function, and the strtolower function, which we learned about.0156

arg is going to refer to an argument that you would pass to these functions.0163

In our script, by passing a function, the function name by the function GET variable, and the function argument by the arg GET variable,0170

what we can do is set up our code so that it will run the specified function on the argument that was requested.0180

The first thing we do is: using the ternary operator, we create short versions of our GET variables; we call one function and one arg.0187

function, again, is the name of the function, and arg is the argument we will be passing to it.0195

Then, we have a couple of nested control structures.0200

So, the first test we do is: we test if function was not equal to null--so that is saying, "Was function provided as a GET variable?"0204

If that is true, then we go ahead and proceed into that if statement.0211

If not, we are going to output a message and say, "No function was selected."0215

Now, once we get in here, we perform another test with an if statement: is argument not equal to null?0219

So, if function wasn't equal to null, but argument was, then we are going to output a message that says no function argument was provided.0224

If not, we are going to go ahead and enter the if statement group.0232

Within this if statement group, which we enter if function is not null and arg is not null, what we have is a switch statement.0235

It runs over the variable function, which is the name of the function passed in.0244

What it does is: it compares that name to each of these three different cases: date, toUpper, and toLower.0249

If it matches any of those cases, what it is going to do is: it is going to run 0256

that corresponding function with the argument that was passed in by a GET.0259

And if an argument was passed in, but the function name is not one of these four--it is not one of the ones recognized--0266

then it is going to, by default--its default case is going to output a message that says "invalid function was requested."0273

What I have up here is a form I have created that uses the GET method.0279

It makes testing these out a little bit easier; and you can see that it has the three functions selected for which this code can process.0284

If we look at the source code for this, we can see that this Select dropdown box has three options 0294

whose values are date, toUpper, and toLower, which match those cases in our switch statement.0303

So, if I select date, and I pass an argument to it, we know the date function outputs a formatted date,0310

and it does so based on a formatting string we provide to it.0318

And so, I want to output the day, the month, and the year; one way to do that is with the characters j M Y.0321

And if we go ahead and click the Call Function button, we can see that it outputs the current date, June 27, 2011.0328

Likewise, if we do strtoupper, and we pass it a lowercase string, and we call the function, the result we get is turned to all uppercase.0337

Now, if we use the strtolower function, and we put an uppercase string, and we call it, it is going to convert it to lowercase.0350

So, as you can see, by passing in the function name and an argument value, and then using this set of nested control structures,0361

here we have a switch statement nested within an if statement, nested within another if statement.0369

What we do is: we compare one of the GET variables (in this case, function) to a bunch of different cases.0375

And then, we use the other argument, the other GET variable passed in, to go ahead and run a function based off of that.0380

So, that is how you can make use of nested conditional control structures.0388

Now, I just want to talk about coding conditions that we are going to use for nested control structures.0395

The way it is going to work is: when you nest a control structure within another one, 0401

you are going to indent the entire nested control structure one indent deeper than the enclosing structure.0406

And we saw that here in nested.php--if we look at the code of that, we can see that here, we have an if statement,0412

and within that, we have nested a switch statement.0420

And as you can see, the switch statement is one indent further than the enclosing control structure.0424

And that said, when you do indent, when you do nest a control structure, the same indentation rules should apply for that control structure.0433

For example, we know that for a switch statement, all of the case statements are one indent deeper than the switch keyword.0441

So, when we nest a switch statement within an if statement, we still indent all of these one extra indent.0446

By the time we get down to these statements here, based on our rules that we have, we have this break statement 0452

that is indented four indents deep: one for this if, one for this switch, one for this case, and one for indenting the case statements.0457

So now, I just want to talk a little bit about debugging control structures.0474

As you can see, when you start adding a lot of nested control structures, the code can get very complicated.0476

You get a lot of test conditions, a lot of curly braces, a lot of semicolons, a lot of break statements...things that are easy to mess up, on occasion.0481

So, debugging them can be quite challenging.0493

Common questions you might be asking yourself are, "Why is the code in this if statement not executing when it is supposed to?"0496

"I have supplied the inputs that I thought were supposed to make it happen; why is it not happening?"0502

On the converse of that, "Why isn't the code in a particular if statement executing?" which is right here.0506

And some of the common errors that occur in our control structures are incorrectly specifying test conditions for your control structures,0512

for example, an if test condition; forgetting a break statement in a switch statement; and then also0520

one that can be the most deceiving is incorrectly placing or omitting an opening or closing curly brace.0527

Let's look at the first one, incorrectly specified test conditions.0534

If we go back to our nested.php...let's say we misspelled date here--we put date1, for example.0538

If we go to our code (this is the code behind nested.php), and we change date to date1 and save it,0547

and we refresh the page, now when we go up here and we try to run our date function, and we try to output a formatted date,0556

and we call the function--instead of getting a formatted date, we are getting "invalid function requested."0570

Why is that? Well, what happened is: we specified a function called date.0575

However, when we went through our switch statement (and actually, this is not the updated version,0582

because this was hard-coded into the HTML; let's go look at the code), what is going to happen is: it is going to have a function value;0587

it is going to have an argument value; when it enters the switch statement it is going to have,0594

the function variable is going to be set to date, and it is going to be looking for date.0598

It doesn't find it here, because we have mistyped it; it doesn't find it here; it doesn't find it here.0602

So, what does it do? It outputs a default statement, which says "invalid function was requested."0606

That is one way where misspelling a test condition can cause problems.0610

Another one could be if we leave out a break statement.0617

For example, let's say we leave out the break statement here.0620

We know from what we learned about the switch statement that, once a case is matched within a switch function,0622

every statement is executed until a break or the end of the switch statement is reached.0629

By leaving out the break statement here, what is going to happen is: if we select date, and it matches,0634

we are going to echo this statement, and instead of breaking out of this switch statement and back into whatever statement follows it,0640

we are going to go down here and execute the next line of code it finds, which is this echo statement.0646

So, this statement is going to be echoed, as well; then, it reaches a break, and it's going to break out.0652

We save this, and we refresh it, and we try to run the same thing as before.0657

Now, we have corrected...well, it looks like it already did it, but let me do it anyway...0666

What is going to happen is: we call the function; it is going to output the date, as we expected.0673

But then also, what it is going to do is: it is going to output that next line of code, which as we saw, was strtoupper.0679

What it is going to do is convert that argument we passed in, which was a date formatting string, and just capitalize it and output it.0685

And this could go even a step further: let's say we forgot to include the break statement here--then it is also going to call the strtolower function.0692

So, if we refresh this page again, which is going to submit the same GET values, we can see, it also added it in lowercase.0700

So, that is one error that can also happen with control structures.0707

Let me go ahead and fix these back, and save it and reload it, just to make sure everything is working as normal.0711

OK, I'll test out one of the functions; OK, so everything is working as it is supposed to.0726

Those are the two problems that can often happen, that we just looked at: incorrectly specified test conditions and the forgetting of a break statement.0736

Also, you can incorrectly place or omit a curly brace, which can cause a lot of problems.0745

It makes it hard to figure out what is going on, because PHP is going to give you an error, but usually the error says "error occurred on line 21."0752

But maybe the error actually didn't occur on line 21; it occurred earlier in the file--and I'll show what that looks like now.0758

If we go and look at, for example...we are going to look at this script called debugTest.php.0765

If we go and look at it in the code, we have the same form at the beginning that allows us to select a function and an argument.0777

And then, what it does is: we have a similar code as in the nested.php, except we'll just remove this inner switch statement.0790

And instead of the switch statement, I have just put an if statement that always evaluates true, and instead of 0799

calling the function, it just outputs a lot of sample text.0807

And the reason I put...you will see why I put so many sample text lines here in a minute.0810

When I go ahead and run this form, what it should do is: if I pass it a valid function name and a valid argument,0815

it should reach here and output all of these sample lines of text.0822

So, if we go and look at debugTest, and I call the function j M Y (it is not even a matter of what I put in, because0825

we are not calling the functions anymore), and press Call Function, you can see, it outputs all of these lines of sample text.0833

Now, one error that is common, that can cause a lot of problems, is: let's say we forget this last closing brace for the if statement.0840

We save it, and you might look at it, and everything might look OK, so we go ahead and we run the file.0848

And if we refresh the page to run it again with the same values, we are going to get an error.0854

It says you have an unexpected error on line 76; so if we go and look back here, the error that we omitted was all the way up here.0859

But it is saying the error is occurring on line 76.0868

Now, the reason that that is happening is: if we look at this from the PHP Interpreter's point of view, for this internal if statement,0872

once it reaches this opening bracket, it evaluates all of these statements as being part of this if statement.0880

When it reaches the first closing bracket, it says, "OK, I am done with this if statement."0886

Then, when it reaches the next closing bracket, it is going to say, "I'm done with this statement here."0891

And in this case, because there wasn't a third closing bracket for this if statement up here, when PHP reaches the end of the file,0897

it is going to say, "Hey, I never received a closing brace for this if statement up here."0903

It is supposed to see three different braces, and that is why it points to the error down here, because it works inward out,0907

in that it sees, "OK, this if statement was closed; this if statement was closed; but this first one wasn't."0916

So, even though we omitted the curly brace on this most internal if statement, it is generating an error for out here.0922

And as you can see, the error says "unexpected end"; and what that is meaning is that it reached the end of the file,0930

and it was looking for a closing curly brace for this if statement.0937

So, that is one error that can really deceive you, because you might be looking at it and saying, "Well, there is no error on line 76."0941

And the reason is because it is a brace that was maybe omitted...0948

And the reason I put several sample text lines here is to demonstrate 0951

how it is going to show the error on a line way down further from where it occurred.0956

For example, this is something that can happen, and it may throw you an error that doesn't make sense, and that is why:0963

because you may have omitted a curly brace 100 lines prior in your code.0969

So, if we go ahead and put this curly brace back in and appropriately close that if statement, and we run it again,0973

everything should work out fine; and there it is.0978

One of the useful techniques you can do for debugging conditional control structures is tracing the execution of your code, 0985

which is kind of what we did, where we look through the code, and for example, we looked at debug.txt.0991

Or actually, if we go to nested.php, we can say, "OK, let's say we provided a function and an argument variable as GET variables."0999

So, we would trace down our code, and we would say, "OK, start here; function is not equal to null."1008

"OK, I'm in here," and we're going to proceed further down; "Argument is not equal to null; I enter here."1013

Then we go to function, and then we go through and evaluate what the different case statements are and say,1018

"OK, is it compared to date?" If it does, we echo this, we break out of it, and then we break all the way back out to the beginning.1023

That is tracing through your code and visually reasoning where the code is going to progress.1030

One trick you can do is to include echo statements at the beginning of each conditional statement, or conditional control structure, 1037

or switch case, with a brief message that is going to let you know that the statement group or case was entered.1044

What that is going to do is (and you only use this when you are debugging, because it is going to output messages 1051

that you wouldn't want to see on a production site): let's say you know that 1055

you are evaluating an if condition that is three if's deep within your file.1060

If you put a debug statement at the beginning of every time you enter an if statement,1066

then you know that, when you look at your output when you run a test--you should see three debug statements.1070

And if you don't, it gives you a clue: if you only see one, or if you only see two, it gives you a clue as to maybe where your error is occurring.1075

Maybe you are not entering a particular if statement--when the debug statement doesn't show up, 1081

you can say, "Well, why didn't I enter this if statement?" and it can clue you in to where that error is happening.1086

So, if we actually go back and look at another file called debugging.php, it is the same file as nested.php,1091

except that it has debug statements added.1099

So, if we go to debugging.php, and we look at the code, we can see that, starting from the first if statement,1105

after each if statement was entered, we output a small statement that says "debug: function was not equal to null," because that is this test condition here.1112

And then, once we enter the second if statement, we say "argument not equal to null."1122

Then, for each case, so that we know when we have entered a case--we have matched a case in our switch function--1126

we also echo a debug statement: this one says, "OK, we are calling the date function."1131

Here, we are calling the strtoupper function.1135

What that will do is let you trace through and make sure you are going through all of the conditional control structures 1138

that you are supposed to, meaning that this test condition here was met, 1143

this test condition here was met, and this test condition here was met, for example, if we were using the date function.1146

If we go back now, with these debug statements included, and we run our code,1153

and call the function, we see the output of our debug statements.1161

We can see the first one, debug: function is not equal to null; so that tells us, "OK, we have successfully gotten to this first if statement."1165

debug: argument not equal to null--well, that debug statement means that we got into the second if statement.1173

debug: calling date--that means that we matched the date case in our switch function.1180

And so, therefore, we know that we have gone through and met all of the test conditions that we were supposed to meet for our script,1185

and that provides a way of giving us feedback, in case there is an error.1191

For example, if I go back over to...once again, go to change this date to date1 so that it doesn't match, so we have an error there,1195

and we save it and run the script again, two things are going to happen.1212

One is: we are not going to get the formatted date; we are going to see an unexpected debug statement,1218

saying the default case was reached (which--we are going to wonder, "Why is that?).1223

And then, we are going to see "invalid function requested."1226

If we go back and look at our code and trace through that (and let's look at the actual code),1228

well, in the output, we first saw that function not equal to null and argument not equal to null debug statements were output.1236

So, we know that we have entered this if statement; we know that we have entered this if statement.1243

The next debug statement that occurs in our output is "default case reached."1248

Let's continue tracing through the program; we are in this if statement; we enter the function statement.1253

We should be hitting this debug statement here, but instead, we are outputting "default case is reached,"1258

which means we are reaching a default case, which means that, for whatever reason, the value that we expected 1263

to match the date case up here didn't match.1269

And sure enough, if we go ahead (this will clue us in) and say, "Wait a minute, why didn't the date case match?"1272

OK, we had a typo on the date; and what that will allow you to do is: then you can go back and refresh the page,1276

and you can see that it is working now.1285

And so, that is a way to help you debug very complex nested control structures.1287

It is quite a useful technique of just outputting simple debug statements, as they are called, 1292

while you are in development, to make things easier, to figure out what is going on.1298

For today's homework challenge, I want to have you do something kind of similar to what we did today1303

with our script that allowed you to select a function and an argument.1307

And it is going to accept three GET parameters: one called operation, one called leftOp, and one called rightOp.1311

What these are going to refer to: operation is going to refer to one of the four basic arithmetic operations.1317

leftOp and rightOp are going to refer to left and right operands of an arithmetic operation.1323

We are going to let operation take on one of four different values: it can be add, subtract, multiply, or divide.1329

And in this case, we are using these abbreviated strings.1337

And so, what is going to happen is: if it receives a leftOp and a rightOp variable from GET, 1341

and it receives an operation that is one of these four values, it is going to perform that operation on these values.1347

Now, what I would like you to do is have it output an error message if no operation is provided1353

(so operation would be equal to null, if we are using the short variables that we have been using with the ternary operator),1358

it is going to output an error message in both the leftOp (and that is the keyword here, AND, which is going to imply a logical operator),1366

AND rightOp are NOT provided (NOT also--that is going to denote a logical operation.1372

Then, it will also output an error message if you provide an operation value, but is not one of the four that are allowed.1382

And then, finally, if the user tries to divide by 0, I want you to output a message.1390

Your solution is going to look similar to what we did today with the nested.php example.1395

in that you should be using nested if, else, and switch statements, and your switch statements should make use of the default case.1399

That will allow you to achieve all of the functionality we have just described.1406

And then, what you need to do is test each of the different cases.1411

Supply some different variables, leftOp, rightOp, and operations; you are going to test 1414

that all of the different operations work (addition, subtraction, multiplication, and division), 1419

along with providing different variable leftOp and rightOp numbers to make sure that they are performing the operations.1423

The other thing that you are going to do is: you are going to try to divide by 0, to make sure that you get that divideByZero error.1431

And then, after you have done that (or if you are having problems figuring out how to get it),1436

I want you to go ahead and add debug statements to each conditional structure, like we did in our example today.1440

So, once you enter each if statement, add a debug statement that says "debugging if statement number 1."1445

And then, also do that for each case in the switch statement.1451

So, for example, if you hit the case add when you are comparing the variable operation against a number of cases,1453

and you compare it against add, when it hits that case, you would output a debug statement saying "performing the addition operation."1462

That will give you practice using the debug statements.1470

And then, just one other note is to be sure to indent your code properly, and make sure you are not missing any curly braces or break statements.1473

And just follow the coding conventions that we have talked about in today's lesson.1481

Thank you for watching; I look forward to seeing you next time.1486