In this tutorial we're going to be talking about another Selection Statement or a Control Statement called the SWITCH Statement. And it's an elegant statement because it allows you to eliminate multiple different conditions IF, ELSE IF ELSE IF and consolidate it into one single line of code. And we'll start with an example of this in FileMaker. If you open up the ScriptMaker in FileMaker and open up any script that's there and put an IF Statement inside of your script list. Open that up to go into the Calculation Dialog and you'll see that there's a Case Function. And the Case Function's quite elegant in that it allows you in a single line of code to test against multiple different conditions and having multiple different results based upon those conditions. So for instance we could test against the variable animal and say that if animal is equal to cat then meow. If animal is equal to dog then bark and lastly have a result of a silent if we don't know what the animal is. You can do the same elegant line of conditioning in PHP using the SWITCH Statement. So let's open up our file 0302.php and we'll show an example of doing this. We'll use the same example that we just used in FileMaker. Our animal is equal to cat let's say. And now we'll use a SWITCH Statement. And we'll say that we want to switch across multiple different evaluations of the variable animal, so we put that in parenthesis. And then our conditions are going to be encapsulated in open and closing curly brackets. Now all we need to use is the Case Statements just like in FileMaker. Case and then we put what we're comparing against. Case is cat then and we use a colon not a semi-colon but a colon and we can put the resulting code after that. Echo meow. Case dog. Then we'll echo bark. And then lastly we have a default so if it's not any of those conditions then default is going to be silent. Now let's go ahead and open this up in our browser and see what our results show. And notice that we're getting every single output. We're getting meow, bark and silent. And the reason why is because in the SWITCH Statement it will evaluate every condition unless it's explicitly told not to. So even though the Case Statement is not true it's still evaluating the Case Statement and then going onto to execute the statement after that. We have to explicitly tell it when the condition is true to stop evaluating. And you do that with the Break Statement. So after every condition you need to make sure the Break Statement so that it stops the evaluation. Now we have meow and if we change this to a dog, silent because nothing's true. Aha! I misspelled dog. And now we have bark.
| Course: | FileMaker and PHP Foundations |
| Author: | Lance Hallberg |
| SKU: | 34393 |
| ISBN: | 978-1-61866-077-0 |
| Release Date: | 2012-12-07 |
| Duration: | 7.5 hrs / 97 lessons |
| Work Files: |
Yes |
| Captions: | No |
| Compatibility: |
Vista/XP/2000, OS X, Linux QuickTime 7, Flash 8 |