-
Notifications
You must be signed in to change notification settings - Fork 16
/
loops.html
268 lines (249 loc) · 15.6 KB
/
loops.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
---
title: Looping the loop
---
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>PHP101 - {{ page.title }}</title>
<link rel="stylesheet" href="stylesheets/styles.css">
<link rel="stylesheet" href="stylesheets/pygment_trac.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="javascripts/main.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
</head>
<body>
<header>
<h1>PHP101</h1>
<p>For the absolute beginner</p>
</header>
<div id="banner">
<span id="logo"></span>
<a href="https://github.com/ss23/php-tutorial" class="button fork"><strong>View On GitHub</strong></a>
</div><!-- end banner -->
<div class="wrapper">
{% include nav.html %}
<section>
<h2>Going deeper</h2>
<p>If you've been paying attention, you remember that in <a href="part2.html">Part Two</a> I gave you a quick crash course in PHP's basic control structures and operators. I also showed you how PHP can be used to process the data entered into a Web form. In this tutorial, I'm going to delve deeper into PHP's operators and control structures, showing you two new operators, an alternative to the if-else() family of conditional statements, and some of PHP's more interesting loops. So keep reading... this is just about to get interesting!</p>
<h2>Switching things around</h2>
<p>An alternative to the if-else() family of control structures is PHP's switch-case() statement, which does almost the same thing. It looks like this:</p>
{% highlight php %}<?php
switch (decision-variable) {
case condition:
// Do something
case condition:
// Do something else
}
?>{% endhighlight %}
<p>Depending on the value of the decision variable, the appropriate case() block is executed. A default block can also be created, to handle all those occasions when the value of the decision variable does not match any of the listed case() conditions.</p>
<p>I'll make this a little clearer by re-writing one of my earlier examples in terms of the switch() statement:</p>
{% highlight php %}<?php
// Get form selection
$day = $_GET['day'];
// Check value and select appropriate item
switch ($day) {
case 1:
$special = 'Chicken in oyster sauce';
break;
case 2:
$special = 'French onion soup';
break;
case 3:
$special = 'Pork chops with mashed potatoes and green salad';
break;
default:
$special = 'Fish and chips';
break;
}
?>
<h2>Today's special is:</h2>
<?php echo $special; ?>{% endhighlight %}
<p>There are a couple of important keywords here:</p>
<ul>
<li>The break keyword is used to break out of the switch() statement
block and move immediately to the lines following it.</li>
<li>The default keyword is used to execute a default set of statements
when the variable passed to switch() does not satisfy any of the
conditions listed within the block.</li>
</ul>
<p>A common newbie mistake here is to forget the break at the end of every case() block. Remember that if you forget to break out of a case() block, PHP will continue executing the code in all the
subsequent case() blocks it encounters. Note howerever, this <em>could</em> be intended behaviour in some cases. Try think of an example where you might want to not have a break there yourself.</p>
<p>For more on the switch() statement, see <a href="http://www.php.net/manual/en/control-structures.switch.php">http://www.php.net/manual/en/control-structures.switch.php</a>.</p>
<h2>Creative conditionals</h2>
<p>Normally, when creating and processing forms in PHP, you would place the HTML form in one file, and handle form processing through a separate PHP script. However, with the power of conditional statements at your disposal, you can combine both pages into one.</p>
<p>How do you do this? Simple. All you need to do is assign a name to the form submit control, and then check whether the special $_POST container variable contains that name when the script first loads up. If it does, the form has already been submitted, and you can process the data; if it does not, that the user has not submitted the form and you therefore need to generate the initial, unfilled form. Thus, by testing for the presence or absence of this submit variable, a clever PHP programmer can use a single PHP script to generate both the initial form, and the output after it has been submitted, as appropriate.</p>
<p>Here's a simple example:</p>
{% highlight php %}<?php
// If the "submit" variable does not exist, the form has not been submitted - display initial page
if (!isset($_POST['submit'])) {
?>
<form method="post"><!-- If we omit the action parameter, it will post to the page we're currently on -->
<label for="age">Enter your age:</label><input name="age" size="2">
<input type="submit" name="submit" value="Go">
</form>
<?php
} else {
// If the "submit" variable exists, the form has been submitted - look for and process form data
// Display result
$age = $_POST['age'];
if ($age >= 21) {
echo 'Come on in, we have alcohol and music awaiting you!';
} else {
echo "You're too young for this club, come back when you're a little older";
}
}
?>{% endhighlight %}
<p>As you can see, the script contains two pages: the initial, empty form and the result page generated after hitting the submit button. In order to decide which page to display, the script first tests for the presence of the $_POST['submit'] variable. If it doesn't find it, it assumes that the form has yet to be submitted, and displays the initial list of days. Once the form has been submitted, the same script will be called to process the form input. This time, however, the $_POST['submit'] variable will be set, and so PHP will not display the initial page, but rather the page containing the result message.</p>
<p>Note that for this to work, your submit button must have a value assigned to its "name" attribute, and you must check for that value in the primary conditional statement. And in case you were wondering, the $_SERVER array is a special PHP variable which always holds server information, including the path and name of the currently executing script.</p>
<p>Next up, loops.</p>
<h2>One by one</h2>
<p>For those of you unfamiliar with the term, a loop is a control structure that enables you to repeat the same set of php statements or commands over and over again (the actual number of repetitions can be a number you specify, or depend on the fulfillment of one or more conditions).</p>
<p>Now, last time out you saw a few comparison and logical operators, which help in building conditional statements. Since this segment of the tutorial is going to focus on loops, this is an appropriate time to introduce you to PHP's auto-increment and auto-decrement operators, which see a lot of use in this context.</p>
<p>The auto-increment operator is a PHP operator designed to automatically increment the value of the variable it is attached to by 1. It is represented by two "plus" signs (++). This snippet of code should explain it:</p>
{% highlight php %}<?php
// Define $total as 10
$total = 10;
// Increment it
$total++;
// $total is now 11
echo $total;
?>{% endhighlight %}
<p>Thus, <code>$total++</code> is functionally equivalent to <code>$total = $total + 1</code>.</p>
<p>There's a corresponding auto-decrement operator (-), which does exactly the opposite:</p>
{% highlight php %}<?php
// Define $total as 10
$total = 10;
// Decrement it
$total--;
// $total is now 9
echo $total;
?>{% endhighlight %}
<p>These operators are frequently used in loops, to update the value of the loop counter, speaking of which...</p>
<h2>Being square</h2>
<p>The first - and simplest - loop to learn in PHP is the so-called while() loop, which looks like this:</p>
{% highlight php %}<?php
while (condition) {
// Do something
}
?>{% endhighlight %}
<p>In this case, so long as the condition specified evaluates as true. Remember what you learned in <a href="part2.html">Part Two</a>? The PHP statements within the curly braces will continue to execute. As soon as the condition becomes false, the loop will be broken and the statements following it will be executed.</p>
<p>Here's a quick example which demonstrates the while() loop:</p>
{% highlight php %}<form action="squares.php" method="POST">
Print all the squares between 1 and <input type="text" name="limit" size="4" maxlength="4">
<input type="submit" name="submit" value="Go">
</form>{% endhighlight %}
<p>This is a simple form which asks the user to enter a number. When the form is submitted, the PHP script that is invoked should take this number and print the squares of all the numbers between 1 and the entered value. With a while() loop, this is simplicity itself:</p>
{% highlight php %}<?php
// Set variables from form input
$upperLimit = $_POST['limit'];
$lowerLimit = 1;
// Keep printing squares until lower limit = upper limit
while ($lowerLimit <= $upperLimit) {
echo ($lowerLimit * $lowerLimit) . ' ';
$lowerLimit++;
}
// print end marker
echo 'END';
?>{% endhighlight %}
<p>This script uses a while() loop to count forwards from 1 until the values of $lowerLimit and $upperLimit are equal.</p>
<h2>Loop first, ask questions later</h2>
<p>The while() loop executes a set of statements while a specified condition is true. But what happens if the condition is true on the first iteration of the loop itself? In the previous example, if you were to enter the value 0 in the form, the while() loop would not execute even once. Try it yourself and you'll see what I mean.</p>
<p>If you're in a situation where you need to execute a set of statements *at least* once, PHP offers you the do-while() loop. Here's what it looks like:</p>
{% highlight php %}<?php
do {
// Do something
} while (condition)
?>{% endhighlight %}
<p>Let's take a quick example to better understand the difference between while() and do-while():</p>
{% highlight php %}<?php
$x = 100;
// while loop
while ($x == 700) {
echo "Running...";
break;
}
?>{% endhighlight %}
<p>In this case, no matter how many times you run this PHP script, you will get no output at all, since the value of $x is not equal to 700. But, if you ran this version of the script:</p>
{% highlight php %}<?php
$x = 100;
// do-while loop
do {
echo "Running...";
break;
} while ($x == 700);
?>{% endhighlight %}
<p>you would see one line of output, as the code within the do() block would run once.</p>
<p>Let's now revise the previous PHP script so that it runs at least once, regardless of what value is entered into the form:</p>
{% highlight php %}<?php
// Set variables from form input
$upperLimit = $_POST['limit'];
$lowerLimit = 1;
// Keep printing squares until lower limit = upper limit
do {
echo ($lowerLimit * $lowerLimit) . ' ';
$lowerLimit++;
} while ($lowerLimit <= $upperLimit);
// print end marker
echo ' END';
?>{% endhighlight %}
<p>Thus, the construction of the do-while() loop is such that the statements within the loop are executed first, and the condition to be tested is checked afterwards. This implies that the statements within the curly braces would be executed at least once.</p>
<p>Read more about the while() and do-while() loops at <a href="http://www.php.net/manual/en/control-structures.while.php">http://www.php.net/manual/en/control-structures.while.php</a> and <a href="http://www.php.net/manual/en/control-structures.do.while.php">http://www.php.net/manual/en/control-structures.do.while.php</a>.</p>
<h2>Doing it by numbers</h2>
<p>Both the while() and do-while() loops continue to iterate for as long as the specified conditional expression remains true. But what if you need to execute a certain set of statements a specific number of times - for example, printing a series of thirteen sequential numbers, or repeating a particular set of <td> cells five times? In such cases, clever programmers reach for the for() loop...</p>
<p>The for() loop typically looks like this:</p>
{% highlight php %}<?php
for (initial value of counter; condition; new value of counter) {
// Do something
}
?>{% endhighlight %}
<p>Looks like gibberish? Well, hang in there for a minute...the "counter" here is a PHP variable that is initialized to a numeric value, and keeps track of the number of times the loop is executed. Before each execution of the loop, the "condition" is tested. If it evaluates to true, the loop will execute once more and the counter will be appropriately incremented; if it evaluates to false, the loop will be broken and the lines following it will be executed instead.</p>
<p>Here's a simple example that demonstrates how this loop can be used:</p>
{% highlight php %}<?php
// Define the number
$number = 13;
// Use a for loop to calculate tables for that number
for ($x = 1; $x <= 10; $x++) {
echo "$number x $x = ".($number * $x)."<br>";
}
?>{% endhighlight %}
<p>The first thing I've done here is define the number to be used for the multiplication table. I've used 13 here - for no reason other than that it rhymes with "green".</p>
<p>Next, I've constructed a for() loop with $x as the counter variable, initialized it to 1. and specified that the loop should run no more than 10 times. The auto-increment operator (discussed earlier) automatically increments the counter by 1 every time the loop is executed. Within the loop, the counter is multiplied by the number, to create the multiplication table, and echo() is used to display the result on the page.</p>
<h2>Turning the tables</h2>
<p>As you just saw, a for() loop is a very interesting - and useful - programming construct. The next example illustrates its usefulness in a manner that should endear it to any HTML programmer.</p>
{% highlight php %}<form method="post">
Enter number of rows <input name="rows" type="text" size="4"> and columns <input name="columns" type="text" size="4"> <input type="submit" name="submit" value="Draw Table">
</form>
<?php
if (isset($_POST['submit'])) {
echo "<table width = 90% border = '1' cellspacing = '5' cellpadding = '0'>";
// set variables from form input
$rows = $_POST['rows'];
$columns = $_POST['columns'];
// loop to create rows
for ($r = 1; $r <= $rows; $r++) {
echo "<tr>";
// loop to create columns
for ($c = 1; $c <= $columns; $c++) {
echo "<td></td>";
}
echo "</tr>";
}
echo "</table>";
}
?>{% endhighlight %}
<p>As you'll see if you try coding the same thing by hand, PHP's for() loop just saved you a whole lot of work! And it looks good too - take a look at the source code of the dynamically generated table, and you'll see that it's nicely formatted, with line breaks at the end of every table cell and row. This magic is accomplished by forcing a carriage return with in every call to echo().</p>
<p>For more examples of the for() loop in action, visit <a href="http://www.php.net/manual/en/control-structures.for.php">http://www.php.net/manual/en/control-structures.for.php</a>.</p>
<p>Loops are frequently used in combination with one of PHP's more complex data types, the animal known as the array. That's a whole topic in itself, and in fact I'm going to discuss it in detail in the next segment of this tutorial. Then I'm going to show you how arrays, loops and forms all work together to make the creation of complex Web forms as easy as eating pie. All that and more in <a href="part4.html">Part Four</a>.</p>
</section>
<footer>
<p><small>Hosted on GitHub Pages — Theme by <a href="http://twitter.com/#!/michigangraham">mattgraham</a></small></p>
</footer>
</div>
<!--[if !IE]><script>fixScale(document);</script><!--<![endif]-->
</body>
</html>