Arrays
Indexed arrays
- Open course/indexed_arrays.php
<h2>Initialize array elements with index</h2>
<div class="margin-3">
<?php
$students[0] = 'John Doe';
$students[1] = 'Jane Doe';
$students[2] = 'Jeff Smith';
for ($i = 0; $i < count($students); $i++) {
echo "<p> Student $i = $students[$i] </p>\n";
}
?>
</div>
<h2>Initialize array elements without index</h2>
<div class="margin-3">
<?php
$teachers[] = 'Michaël Cloots';
$teachers[] = 'Jan Janssen';
$teachers[] = 'Patrick Verhaert';
for ($i = 0; $i < count($teachers); $i++) {
echo "<p> Teacher $i = $teachers[$i] </p>\n";
}
?>
</div>
<h2>Initialize array with [ ] </h2>
<div class="margin-3">
<?php
$teachers = ['Michaël Cloots', 'Jan Janssen', 'Patrick Verhaert'];
for ($i = 0; $i < count($teachers); $i++) {
echo "<p> Teacher $i = $teachers[$i] </p>\n";
}
?>
</div>
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
TIP
It's common practice to use a plural noun as array variable name (as an array usually contains multiple elements)
- Similar to other variabes, arrays don't need to be declared
- Arrays can be initialized immediately
- Use an index (between square brackets
[]
) to inititalize an array element, as in$students[1] = 'Jane Doe';
- If you initialize an array element without supplying an index, a new array element is added at the end of the array, as in
$teachers[] = 'Jan Janssen';
- An array can be initialized at once by putting the element values (seperated by commas) between square brackets
[]
, as in$teachers = [ 'Michaël Cloots' , 'Jan Janssen', 'Patrick Verhaert' ];
- An alternative (older) way of doing this uses the PHP
array()
function:$teachers = array('Michaël Cloots' , 'Jan Janssen', 'Patrick Verhaert');
- An alternative (older) way of doing this uses the PHP
- Use an index (between square brackets
- You can loop over all elements of an array using a
for
structure. The PHP functioncount()
can be used to get the number of elements in an array.
REMARK
As in most programming languages, the array indexes start at 0. The index of the last element equals count(...) - 1
, and, hence, the condition in the for
loop is of the form $i < count(...)
.
Associative arrays
- Open course/associative_arrays.php
<div class="margin-3">
<?php
$scoresJohn['PHP'] = 13;
$scoresJohn['Business essentials'] = 8;
$scoresJohn['English 2'] = 18;
echo "<p> John's score for PHP = {$scoresJohn['PHP']} </p>\n";
echo "<p> John's score for Business essentials = {$scoresJohn['Business essentials']} </p>\n";
echo "<p> John's score for English 2 = {$scoresJohn['English 2']} </p>\n";
?>
</div>
<h2>foreach</h2>
<div class="margin-3">
<?php
$scoresJane = ['PHP' => 17, 'Business essentials' => 14, 'English 2' => 10];
?>
<p> Jane's scores: </p>
<ul>
<?php
foreach ($scoresJane as $score) {
echo "<li> $score </li>\n";
}
?>
</ul>
</div>
<div class="margin-3">
<?php
foreach ($scoresJane as $course => $score) {
echo "<p> Jane's score for $course = $score </p>\n";
}
?>
</div>
<h2>compact</h2>
<div class="margin-3">
<?php
$php = 9;
$businessEssentials = 11;
$english2 = 16;
$scoresJeff = compact('php', 'businessEssentials', 'english2');
?>
<h3>var_dump</h3>
<?php
ini_set('xdebug.overload_var_dump', 0);
var_dump($scoresJeff);
?>
<h3>print_r</h3>
<?php
print_r($scoresJeff);
?>
</div>
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
- Associative arrays use descriptive strings (e.g. course names) as index or key, as in
$scoresJohn['PHP'] = 13;
to initialize a single element of an associative array$scoresJane = ['PHP' => 17, 'Business essentials' => 14, 'English 2' => 10];
to initialize an associative array at once
REMARK
In order to interpolate an element of an associative array in a double quoted (or heredoc) string, it should be wrapped in single curly braces { }
to "isolate" it, as in echo "<p> John's score for PHP = {$scoresJohn['PHP']} </p>\n";
- Obviously, you can use a concatenated string to generate the same output:
echo "<p> John's score for PHP = " . $scoresJohn['PHP'] . "</p>\n";
foreach
- The
foreach
loop is used to loop over all elements in an associative array - There are 2 variants of this loop, depending on whether you want "access" to the values and/or the keys of the array elements
foreach ($array as $value){...}
foreach ($array as $key => $value){...}
REMARK
The foreach
loop can also be used for indexed arrays, as illustrated below for our first example (with the array $students
)
foreach ($students as $student){
echo "<p> $student </p>\n";
}
// OUTPUT:
//John Doe
//Jane Doe
//Jeff Smith
foreach ($students as $i => $student){
echo "<p> Student $i = $student </p>\n";
}
// OUTPUT:
//Student 0 = John Doe
//Student 1 = Jane Doe
//Student 2 = Jeff Smith
2
3
4
5
6
7
8
9
10
11
12
13
14
15
compact
- The PHP function
compact()
provides an easy way to construct an associative array from a set of variables$scoresJeff = compact('php', 'businessEssentials, 'english2')
is a shorthand for$scoresJeff = [ 'php' => $php, 'businessEssentials' => $businessEssentials, 'english2' => $english2]
- Any key strings that don't have matching variable names are skipped
var_dump() and print_r()
- The PHP functions
var_dump()
andprint_r()
both show information (content) about a variable on screen- Homestead uses Xdebug, which overloads the default PHP version of
var_dump()
. The statementini_set('xdebug.overload_var_dump', 0)
- that can be globally added e.g. to shared/meta.php - disables Xdebug when usingvar_dump()
.
- Homestead uses Xdebug, which overloads the default PHP version of
Two-dimensional arrays
- Open course/two_dimensional_arrays.php
<h2>Indexed two-dimensional arrays</h2>
<div class="margin-3">
<?php
//first index: students
//second index: courses
$scores[0][0] = 13;
$scores[0][1] = 8;
$scores[0][2] = 18;
$scores[1][0] = 17;
$scores[1][1] = 14;
$scores[1][2] = 10;
$scores[2][0] = 9;
$scores[2][1] = 11;
$scores[2][2] = 16;
echo "<p> Score of student 0 for course 2 = {$scores[0][2]} </p>\n";
echo "<p> Score of student 1 for course 1 = {$scores[1][1]} </p>\n";
echo "<p> Score of student 2 for course 0 = {$scores[2][0]} </p>\n";
?>
</div>
<div class="margin-3">
<?php
//rows: students
//columns: courses
$scores = [
[13, 8, 18],
[17, 14, 10],
[9, 11, 16]
];
for ($i = 0; $i < count($scores); $i++){
echo "<p> Scores of student $i: </p>\n";
echo "<ul>\n";
for ($j = 0; $j < count($scores[$i]); $j++){
echo "<li> Course $j: {$scores[$i][$j]} </li>\n";
}
echo "</ul>\n";
}
?>
</div>
<h2>Associative two-dimensional arrays</h2>
<div class="margin-3">
<?php
$scores = [
'John' => ['PHP' => 13, 'Business essentials' => 8, 'English 2' => 18],
'Jane' => ['PHP' => 17, 'Business essentials' => 14, 'English 2' => 10],
'Jeff' => ['PHP' => 9, 'Business essentials' => 11, 'English 2' => 16]
];
echo "<p> John's score for English 2 = {$scores['John']['English 2']} </p>\n";
echo "<p> Jane's score for Business essentials = {$scores['Jane']['Business essentials']} </p>\n";
echo "<p> Jeff's score for PHP = {$scores['Jeff']['PHP']} </p>\n";
?>
</div>
<div class="margin-3">
<?php
foreach ($scores as $person => $scoresPerson) {
foreach ($scoresPerson as $course => $score) {
echo "<p> $person's score for $course = $score</p>\n";
}
}
?>
</div>
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
- A two-dimensional array is a (nested) array that stores another array at each index (instead of a single element)
- Both indexed and associative two-dimensional arrays are possible
- Use 2 pairs of square brackets
[][]
to identify a specific element
- Also higher-dimensional arrays are possible (although they are difficult to manage)