Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
PHP

Welcome back to the world of PHP! I hope you had a good thought about the scenarios I highlighted at the end of the last article. If you understood the use of each operator, it won’t be a difficult task. Anyway, if you have any doubts so far, you are encouraged to contact me codekadiya at gmail dot com.
The main focus in today’s article is going be on control structures available in PHP.
Control Structures
If you think about all the code examples we tried so far, you may notice the fact that they all execute in the sequential order – in the order we have written the lines. In programming, most of the time it is not the only case. We have to make decisions at various points depending on the present data and also to execute a particular set of lines repetitively rather than flowing through the code in sequential manner. That’s exactly the use of control structures, which we are about to learn now.
Making Decisions
If statements
In order to provide a sensible response to the user, your code should be able to make decisions by evaluating the inputs/present data. By doing so, code can take the appropriate action in each user scenario. For example, say you want to display a message to user when the available quantity for a product is zero.
<?php $quantity = 0; if($quantity==0) { echo "Product is out of stock!"; } ?>
We use the if condition to make decisions. The following code block within the pair of curly brackets is executed, only if the condition given within the brackets returns true (remember comparison operators in last article?). In case the condition is false, the following lines within curly brackets are ignored. So in above example, the message is displayed only when products are out of stock.
Often you will want to define an alternative set of lines to be executed if the conditions given to the if condition returns false. The else statement allows just that. Continuing above example, imagine you want to display the quantity available if product is not out of stock. We may modify the code as follows:
<?php $quantity = 7; if($quantity==0) { echo "Product is out of stock!"; } else { echo "Available Quantity: ".$quantity; } ?>
There can be situations where there are more than two ways to respond to the user. Imagine you want to display a different message when quantity is less than 10 but greater than 3; something like “We’ve got only few items with us”. In such situations, we can use any number of elseif statements to check each of the conditions.
<?php $quantity = 3; if($quantity==0) { echo "Product is out of stock!"; } elseif($quantity<10 && $quantity>3) { echo "We’ve got only few items with us.."; } elseif($quantity<=3) { echo "We’re just about to go out of stock.."; } else { echo "Available Quantity: ".$quantity; } ?>
Switch statements
Switch is another possible way in PHP to make decisions. When using switch, a single expression (commonly a value of a variable) is compared against a series of values written as case statements to decide the necessary action. There can be any number of case statements which are having values of simple type (integer, string or double).
<?php $country_code = "lk"; switch($country_code) { case "lk": echo "You are from Sri Lanka"; break; case "us": echo "You are from United States"; break; case "au": echo "You are from Australia"; break; default: echo "Your country is not detected!"; } ?>
At the point of switch, PHP looks for a case statement having a matching value for the variable given within the pair of brackets, which is $country_code in above code. If a match is found, the block of code associated with that case statement is executed. PHP will execute all the following statements until it reaches a break statement. So it is necessary to provide a break statement after the code block of each case statement. If no match is found, the code block associated with the default statement gets executed.
Repetition
Loops are used to repeatedly executing similar set of lines in an automated manner. Say you need to print the string “Hello World” 500 times to the browser. What do you do? Ready to write 500 echo statements?
<?php echo "Hello World<br />"; echo "Hello World<br />"; echo "Hello World<br />"; echo "Hello World<br />"; echo "Hello World<br />"; //............ :-( ?>
Er.. I don’t think so you’ll be much interested in that! Loops are made for that.
While loop
While loop is probably the simplest kind of loop available in PHP. Basically it works by testing a given condition. You can make a given code block to be executed as long as a given condition is true. In other words, loop is stopped once the condition returns false.
<?php $i = 1; while($i<=5) { echo "Hello World<br />"; $i++; } ?>
This is how it works: At the beginning of each iteration, the condition is checked. Only if it returns true, the following code block is executed. If it’s false, while loop is terminated and PHP executes any other lines after the closing curly bracket (it any present).
Most commonly, while loop is used when you are unsure how many iterations are required in your loop (that is why we make use of a condition). You will understand more about this when we do more coding later.
For loop
For loop is another type which is often used in programming. The advantage of for loop is being able to define the things we did in while loop in a more compact manner. The important aspect to keep in mind is the number of iterations should be fixed and you must know the number prior to the loop.
<?php for($i=1;$i<=5;$i++) { echo "Hello World<br />"; } ?>
As you can see, after the for keyword, there are three expressions given within the pair of brackets separated by semicolons. The first expression is executed once at the start, commonly defining the initial value of counter variable. The second is a condition tested before each iteration, usually checking a limit of counter variable – if the condition returns true, the loop continues – otherwise, loop stops. The third expression is executed once at the end of each iteration, usually incrementing/decrementing the counter variable.
At this point, you can think about numerically-indexed arrays which we discussed in a previous article. With loops we can do any operation going through each element present in an array. I assume you can remember the way arrays are accessed using their indexes. I will use the same $fruits array here to show you how we can combine it to work with for loop.
<?php $fruits = array(", "Banana", "Mango", "Apple", "Guava"); echo "Fruits I like: <br />"; echo "<ul>"; for($i=0;$i<5;$i++) { echo "<li>".$fruits[$i]."</li>"; } echo "</ul>"; ?>
I have applied the value of counter variable to the place of index. So at the each iteration of the loop, each element in the array is printed out.
Foreach loop
Think about this- is it possible to easily go through the values in an associative array using a for loop, just as we did above with a numerically-indexed array? Answer is No. Why? For loop has a numeric counter and it’s easy for us to apply it as the index of a numerically-indexed array. But in an associative array it’s not the case. The keys/indexes can be of any type as we discussed earlier (can be a string).
<?php $products = array("Laptop" => 150000, "Mobile Phone" => 43000, "Webcam" => 5000); ?>
Ok, no worries- That’s why we have foreach loop.
<?php $products = array("Laptop" => 150000, "Mobile Phone" => 43000, "Webcam" => 5000); echo "Prices: <br />"; echo "<ul>"; foreach($products as $prod_name=>$price) { echo "<li>".$prod_name." - Rs.".$price."</li>"; } echo "</ul>"; ?>
Foreach loop walks through the associative array assigning the key to $prod_name and value to $price at the each iteration. In other words, in first iternation $prod_name is “Laptop”, value is 150000. In second iteration $prod_name is “Mobile Phone”, value is 43000 and so on till the loop finds the end of the given array. Foreach loop makes the life so much easier to work with arrays in this way!
Do ..While loop
This is probably the least used type of loops, but it is always good to know the way things work. Therefore, I will keep this short. Do..While loop differs from while loop because the condition is checked at the end.
<?php $i = 1; do { echo "Hello World<br />"; $i++; } while($i<=5) ?>
The fact the condition is checked only at the end of each iteration (in contrast to checking the condition before each iteration in other types of loops), results in the code block being executed at least once. For instance, in above example if initially $i was set to 100, still the “Hello World” text will be printed once to the browser, before the loop gets terminated (loop has already iterated once before it finds condition is false).
Breaking out from loops
In some special situations, you will need to stop the execution of a loop in middle rather than performing all iterations.
<?php echo "I'm going to count from 1 to 100.. here I start<br />"; for($i=1;$i<=100;$i++)
{ echo $i."<br />"; if($i==70) { echo "Ohh.. I'm tired at 70!!!!<br />"; break; } } echo "I'm off to sleep...<br />"; ?>
Run the script and check the output. When the loop reaches a break statement, PHP will stop the execution of the loop and execution of the script will continue from the next line after loop closing curly bracket.
Skipping iterations
There is a possibility of jumping to next iteration in a loop, rather than executing the current iteration.
<?php echo "I'm going to count from 1 to 5..<br />"; for($i=1;$i<=5;$i++)
{ if($i==3) { continue; } echo $i."<br />"; } echo "Did I miss something?"; ?>
Again if you check this script, you will notice that “3” is not printed because I have used the continue statement to be executed if the current iteration is 3. When the loop reaches a continue statement, PHP will stop the processing of current iteration and jump to next iteration.
That’s it. Some hints about code formatting:
|
> It is a good practice to indent your code for readability purposes. > Indenting allows programmers to see at a glance which conditions are executed if a condition is satisfied, code blocks for loops etc. Refer to the examples in this article to learn good code indenting. |
We learnt a lot today, didn’t we? It’s time to sign out for today! I assume you have lot of things to experiment this month, so I’m not going to make your life harder ;-). Happy coding till I see you next time!
Post new comment