![]() |
|
This chapter is an important one, we will covers control stuctures. Control structures allow us to control our scripts, to perform different statements, output different output depnding on certain conditions, to perform loops and so forth. Here we’ll have a look at a couple of them. ConditionalsConditionals allow us to perform different statements depending on certain conditions, here is the formal for a simple if statement.We say if(condition is true) then perform a set of actions. Let’s look at a practical example.
It kind of speaks for itself. The > means “greater than”. So “if $a (2) is greater than $b (1) print out ‘the value in $a is greather than the value in $b’”. We can also use else :
This allows us to print out something if the condition is NOT true also. So if it is true it will execute whatever is between the curly braces for the if() statement. Or else it will execute whatever is between the curly braces for the else statement. There’s more, we can use elseif :
This time we used the == operator. If $a is EQUAL to $b, do whatever is in the curly brackets, ELSE IF $a is greater than $b, do whatever is in those curly brackets, OR ELSE do whatever is in the final curly brackets. Conditionals are very useful and it is essential you know how to use them, have a play around. WhileWhile is a function that allows us to perform actionswhile a condition is true. Let’s take a look at an example.Firstly, $var++; means “increment var” meaning “add one to the value of var”. It is the same as $var = $var + 1; . Let’s go thru the steps.
This process repeats until $var reaches the value of 11 , it is then no longer LESS THAN 11 , it is 11 , so the while loop doesn’t execute again and the script finishes. So all the above script would do is count out one to ten.
While is a very useful control structure, if you get deeper into PHP and start working with databases and text files you will use it a lot. Have a play around with it. Putting a condition inside the () after the while statement that will always be true (like 1==1) is not a good idea. It will produce an inifite loop. MoreThe two control structures I have showed you are the most commonly used. There are more but I don’t want this chapter to be too long. So rather than repeating what is already out there available to you, I’ll just direct you to The PHP Manual: Control Structures. There you will find information on all the control structures and exhaustive directions on how to use each of them.Go on to the next chapter to learn how to get deeper into PHP.
No Comments for this page. |
|