forked from ss23/php-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtypes.html
279 lines (267 loc) · 15.7 KB
/
types.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
269
270
271
272
273
274
275
276
277
278
279
---
title: The food factor
---
<!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>A big mistake</h2>
<p>Having spent lots of time travelling around the outer landscape of PHP - learning all about control structures, operators and variables - you're probably bored. You might even be thinking of dropping out right now, and instead spending your time more constructively (or so you think) in front of the idiot box.</p>
<p>That would be a big mistake. And when I say big, I mean humongous.</p>
<p>You see, if you forego this segment of the tutorial for the dubious charms of Ally McBeal, you're going to miss out on one of PHP's coolest variable types. It's a little thing called an array, and I'm not exaggerating when I tell you that once you're on speaking terms with it, you're never going to look at a PHP script the same way again. But hey, don't take my word for it... toss that remote aside and come see for yourself!</p>
<h2>Fruity pizza</h2>
<p>Thus far, the variables we've discussed contained only a single value, such as:</p>
{% highlight php %}<?php
$i = 5;
?>{% endhighlight %}
<p>However, array variables are a different kettle of fish altogether. An array is a complex variable that allows you to store multiple values in a single variable (which is handy when you need to store and represent related information). Think of the array variable as a "container" variable, which can contain one or more values. For example:</p>
{% highlight php %}<?php
// Define an array
$pizzaToppings = array('onion', 'tomato', 'cheese', 'anchovies', 'ham', 'pepperoni');
print_r($pizzaToppings);
?>{% endhighlight %}
<p>Here, $pizzaToppings is an array variable, which contains the values 'onion', 'tomato', 'cheese', 'anchovies', 'ham' and 'pepperoni'. (Array variables are particularly useful for grouping related values together.)</p>
<p>print_r() is a special function that allows you to take a sneak peek inside an array. It's more useful for debugging (finding out why your script doesn't work) than it is for display purposes, but I'll use it here so you can see what's going on under the surface. You do have your server running and your browser open, right?</p>
<p>The various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the element 'onion', you would use the notation $pizzaToppings[0], while 'anchovies' would be $pizzaToppings[3] - essentially, the array variable name followed by the index number enclosed within square braces.</p>
<p>PHP also allows you to replace indices with user-defined "keys", in order to create a slightly different type of array. Each key is unique, and corresponds to a single value within the array.</p>
{% highlight php %}<?php
// Define an array
$fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum', 'green' => 'grape');
print_r($fruits);
?>{% endhighlight %}
<p>In this case, $fruits is an array variable containing four key-value pairs. (The <code>=></code> symbol is used to indicate the association between a key and its value.) In order to access the value 'banana', you would use the notation $fruits['yellow'], while the value 'grape' would be accessible via the notation $fruits['green'].</p>
<p>This type of array is sometimes referred to as a "hash" or "associative array". If you've ever used Perl, you'll see the similarities to the Perl hash variable.</p>
<h2>Eating Italian</h2>
<p>The simplest was to define an array variable is the array() function. Here's how:</p>
{% highlight php %}<?php
// Define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
?>{% endhighlight %}
<p>The rules for choosing an array variable name are the same as those for any other PHP variable: it must begin with a letter or underscore, and can optionally be followed by more letters, numbers and underscores.</p>
<p>Alternatively, you can define an array by specifying values for each element in the index notation, like this:</p>
{% highlight php %}<?php
// Define an array
$pasta[0] = 'spaghetti';
$pasta[1] = 'penne';
$pasta[2] = 'macaroni';
?>{% endhighlight %}
<p>If you're someone who prefers to use keys rather than default numeric indices, you might prefer the following example:</p>
{% highlight php %}<?php
// Define an array
$menu['breakfast'] = 'bacon and eggs';
$menu['lunch'] = 'roast beef';
$menu['dinner'] = 'lasagna';
?>{% endhighlight %}
<p>You can add elements to the array in a similar manner. For example, if you wanted to add the element 'green olives' to the $pizzaToppings array, you would
use something like this:</p>
{% highlight php %}<?php
// Add an element to an array
$pizzaToppings[3] = 'green olives';
?>{% endhighlight %}
<p>In order to modify an element of an array, simply assign a new value to the corresponding scalar variable. If you wanted to replace 'ham' with 'chicken', you'd use:</p>
{% highlight php %}<?php
// Modify an array
$pizzaToppings[4] = 'chicken';
?>{% endhighlight %}
<p>You can do the same using keys. The following statement modifies the element with the key 'lunch' to a different value:</p>
{% highlight php %}<?php
// Modify an array
$menu['lunch'] = 'steak with mashed potatoes';
?>{% endhighlight %}
<h2>Push and pull</h2>
<p>One of the handier construsts or arrays is pushing values on. Consider the following:</p>
{%highlight php %}<?php
$animals = array();
$animals[] = 'cat';
$animals[] = 'dog';
print_r($animals);
?>{% endhighlight %}
<p>When you run the code, you'll see that you have an array just like if you had constructed it with <code>array('cat', 'dog');</code>. You'll find this style of adding elements to arrays most useful when you need to add them dynamically, rather than on construction.</p>
<p>You can also add an element to the end of an existing array with the <code>array_push()</code> function:</p>
{% highlight php %}<?php
// Define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// Add an element to the end
array_push($pasta, 'tagliatelle');
print_r($pasta);
?>{% endhighlight %}
<p>And you can remove an element from the end of an array using the interestingly-named <code>array_pop()</code> function.</p>
{% highlight php %}<?php
// Define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// Remove an element from the end
array_pop($pasta);
print_r($pasta);
?>{% endhighlight %}
<p>If you need to pop an element off the top of the array, you can use the <code>array_shift()</code> function:</p>
{% highlight php %}<?php
// Define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// Take an element off the top
array_shift($pasta);
print_r($pasta);
?>{% endhighlight %}
<p>And the <code>array_unshift()</code> function takes care of adding elements to the beginning of the array.</p>
{% highlight php %}<?php
// Define an array
$pasta = array('spaghetti', 'penne', 'macaroni');
// Add an element to the beginning
array_unshift($pasta, 'tagliatelle');
print_r($pasta);
?>{% endhighlight %}
<p>The <code>array_push()</code> and <code>array_unshift()</code> functions don't work with associative arrays; to add elements to these arrays, it's better to use the <code>$arr[$key] = $value</code> notation to add new values to the array.</p>
<p>The <code>explode()</code> function splits a string into smaller components, based on a user-specified delimiter, and returns the pieces as elements as an array.</p>
{% highlight php %}<?php
// Define CSV string
$str = 'red, blue, green, yellow';
// split into individual words
$colors = explode(', ', $str);
print_r($colors);
?>{% endhighlight %}
<p>To do the reverse, you can use the <code>implode()</code> function, which creates a single string from all the elements of an array by joining them together with a user-defined delimiter. Reversing the example above, we have:</p>
{% highlight php %}<?php
// Define array
$colors = array ('red', 'blue', 'green', 'yellow');
// Join into single string with 'and'
// Returns 'red and blue and green and yellow'
$str = implode(' and ', $colors);
print $str;
?>{% endhighlight %}
<p>Finally, the two examples below show how the <code>sort()</code> and <code>rsort()</code> functions can be used to sort an array alphabetically (or numerically), in ascending and descending order respectively:</p>
{% highlight php %}<?php
// Define array
$pasta = array('spaghetti', 'penne', 'macaroni');
// Returns the array sorted alphabetically
sort($pasta);
print_r($pasta);
print "<br>";
// Returns the array sorted alphabetically in reverse
rsort($pasta);
print_r($pasta);
?>{% endhighlight %}
<h2>Looping the loop</h2>
<p>So that takes care of putting data inside an array. Now, how about getting it out?</p>
<p>Retrieving data from an array is pretty simple: all you need to do is access the appropriate element of the array using its index number. To read an entire array you simply loop over it, using any of the loop constructs you learned about in <a href="part3.html">Part Three</a> of this tutorial.</p>
<p>How about a quick example?</p>
{% highlight php %}My favourite bands are:
<ul>
<?php
$artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses');
// Loop over array and print array elements
for ($x = 0; $x < count($artists); $x++) {
echo '<li>' . $artists[$x] . "</li>\n";
}
?>
</ul>{% endhighlight %}
<p>When you run this script, here's what you'll see:</p>
<blockquote>
<ul>
<li>Metallica</li>
<li>Evanescence</li>
<li>Linkin Park</li>
<li>Guns n Roses</li>
</ul>
</blockquote>
<p>In this case, I've defined an array, and then used the for() loop
to: run through it, extract the elements using
the index notation, and display them one after the other.</p>
<p>I'll draw your attention here to the count() function. This function is one of the most important and commonly used array functions. It returns the size of (read: number of elements within) the array. It is mostly used in loop counters to ensure that the loop iterates as many times as there are elements in the array.</p>
<p>Another thing of note is the usage of <code>\n</code>. If you haven't had a read of <a href="http://php.net/manual/en/language.types.string.php">http://php.net/manual/en/language.types.string.php</a> yet, it might pay to do so. When there is a character like <code>\n</code> contained within double quotes, it's replaced with another value, similiar to how our <code>$variables</code> are. The <code>\n</code> is a newline character. We're using it here to make our output HTML look more readable. Note that this won't effected the rendered HTML, you would have to use <code><br></code> for that. Try it out for yourself - removing the <code>\n</code>, and replacing it with <code><br></code>.</p>
<p>If you're using an associative array, the array_keys() and array_values()functions come in handy, to get a list of all the keys and values within the array.</p>
{% highlight php %}<?php
// Define an array
$menu = array('breakfast' => 'bacon and eggs', 'lunch' => 'roast beef', 'dinner' => 'lasagna');
// returns the array ('breakfast', 'lunch', 'dinner') with numeric indices
$result = array_keys($menu);
print_r($result);
echo "<br>";
// returns the array ('bacon and eggs', 'roast beef', 'lasagna') with numeric indices
$result = array_values($menu);
print_r($result);
?>{% endhighlight %}
<h2>What's that noise</h2>
<p>There is, however, a simpler way of extracting all the elements of
an array: the <code>foreach()</code> loop. (It is similar in syntax to the Perl construct of the same name.) Here's what it looks like:</p>
{% highlight php %}<?php
foreach ($array as $item) {
// Do something with $item
}
?>{% endhighlight %}
<p>A <code>foreach()</code> loop runs once for each element of the array passed to it as argument, moving forward through the array on each iteration. Unlike a <code>for()</code> loop, it doesn't need a counter or a call to <code>count()</code>, because it keeps track of its position in the array automatically. On each run, the statements within the curly braces are executed, and the currently-selected array element is made available through a temporary loop variable.</p>
<p>To better understand how this works, consider this rewrite of the previous example, using the <code>foreach()</code> loop:</p>
{% highlight php %}My favourite bands are:
<ul>
<?php
// Define array
$artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses');
// Loop over it
// Print array elements
foreach ($artists as $a) {
echo '<li>' . $a . "</li>\n";
}
?>
</ul>{% endhighlight %}
<p>Each time the loop executes, it places the currently-selected array element in the temporary variable <code>$a</code>. This variable can then be used by the statements inside the loop block. Since a <code>foreach()</code> loop doesn't need a counter to keep track of where it is in the array, it is lower-maintenance and also much easier to read than a standard <code>for()</code> loop. Oh yeah... and it also works with associative arrays, with no extra programming needed.</p>
<h2>Music for the masses</h2>
<p>In addition to their obvious uses, arrays and loops also come in handy when processing forms in PHP. For example, if you have a group of related checkboxes or a multi-select list, you can use an array to capture all the selected form values in a single variable, to simplify processing. Consider the following example, which illustrates this:</p>
{% highlight php %}<?php
// Check for submit
if (!isset($_POST['submit'])) {
// Display form
?>
<form method="POST">
<input type="checkbox" name="artist[]" value="Bon Jovi">Bon Jovi
<input type="checkbox" name="artist[]" value="N'Sync">N'Sync
<input type="checkbox" name="artist[]" value="Boyzone">Boyzone
<input type="checkbox" name="artist[]" value="Britney Spears">Britney Spears
<input type="checkbox" name="artist[]" value="Jethro Tull">Jethro Tull
<input type="checkbox" name="artist[]" value="Crosby, Stills & Nash">Crosby, Stills & Nash
<input type="submit" name="submit" value="Select">
</form>
<?php
} else {
// or display the selected artists
// use a foreach loop to read and display array elements
if (is_array($_POST['artist'])) {
echo 'You selected: <br>';
foreach ($_POST['artist'] as $a) {
echo "<em>$a</em><br>";
}
} else {
echo 'Nothing selected';
}
}
?>{% endhighlight %}
<p>When the above form is submitted, PHP will automatically create an array variable, and populate it with the items selected. This array can then be processed with a <code>foreach()</code> loop, and the selected items retrieved from it.</p>
<p>You can do this with a multi-select list also, simply by using array notation in the select control's "name" attribute. Try it out for yourself and see... and make sure you tune in for <a href="part5.html">the next PHP 101 tutorial</a>, same time, same channel.</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>