# Arrays and objects

# Indexed arrays

  • Open course/indexed_arrays.php

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
  • As in most programming languages, the array indexes start at 0
  • Arrays can be initialized immediately
    • Use an index (between square brackets []) to initialize 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');

REMARKS

  • As in most programming languages, the array indexes start at 0
  • The index of the last element equals count(...) - 1

foreach loop

  • The foreach loop is used to loop over all elements in an indexed array, in an associative array and in an object
  • There are 2 variants of this loop, depending on whether you want "access" to the values and/or the indexes/keys of the array elements and objects
    • foreach ($array as $value){...}
    • foreach ($array as $index => $value){...} (on indexed arrays)
    • foreach ($array as $key => $value){...} (on associative arrays and objects)

# Associative arrays

  • Open course/associative_arrays.php
  • 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";

# Multidimensional arrays

  • Open course/multidimensional_arrays.php


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 




 
 





 
 
 
 
 
 
 
 



<h1>Multidimensional arrays</h1>
<?php
$students = [
   [
       'name' => 'John',
       'scores' => [
           'PHP' => 13, 'Business Essentials' => 8, 'English 2' => 18
       ],
   ],
   [
       'name' => 'Jane',
       'scores' => [
           'PHP' => 17, 'Business Essentials' => 14, 'English 2' => 10
       ],
   ],
   [
       'name' => 'Jeff',
       'scores' => [
           'PHP' => 9, 'Business Essentials' => 11, 'English 2' => 16
       ],
   ],
];
?>

<article>
   <?php
   echo "<p>The name of the first student = {$students[0]['name']}</p>";
   echo "<p>Jeff's score for PHP =  {$students[2]['scores']['PHP']}</p>";
   ?>
</article>

<article>
   <?php
   foreach ($students as $index => $student) {
       echo "<h2> Scores for student $index: {$student['name']} </h2>\n";
       echo "<ul>\n";
       foreach ($student['scores'] as $key => $score) {
           echo "<li>{$student['name']}'s score for $key = $score </li>\n";
       }
       echo "</ul>\n<hr>\n";
   }
   ?>
</article>
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

Multidimensional arrays

  • A multidimensional 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 or more pairs of square brackets [][] to identify a specific element

# Objects

  • Open course/objects.php


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


 

 
 
 
 
 
 
 
 
 
 



<h1>Objects</h1>
<?php
$students = [
    [
        'name' => 'John',
        'scores' => [
            'PHP' => 13, 'Business Essentials' => 8, 'English 2' => 18
        ],
    ],
    [
        'name' => 'Jane',
        'scores' => [
            'PHP' => 17, 'Business Essentials' => 14, 'English 2' => 10
        ],
    ],
    [
        'name' => 'Jeff',
        'scores' => [
            'PHP' => 9, 'Business Essentials' => 11, 'English 2' => 16
        ],
    ],
];

// convert array to object
$studentsObj = json_decode(json_encode($students));

foreach ($studentsObj as $index => $student) {
    echo "<article>\n";
    echo "<h2> Scores for student $index: $student->name </h2>\n";
    echo "<ul>\n";
    foreach ($student->scores as $key => $score) {
        echo "<li>{$student->name}'s score for $key = $score </li>\n";
    }
    echo "</ul>\n";
    echo "</article>\n";
}
?>
</article>
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

Objects

  • For simple, associative arrays, it's probably sufficient to cast the array to an object: $object = (object) $array;, but this does not work for multidimensional arrays!
  • The cleanest solution is to use the built-in json_ functions: $object = json_decode(json_encode($array), false);
    • You can omit the second parameter of json_decode if it is false
    • Set the second parameter of json_decode to true to convert an object back to an associative array

# Debugging tips

  • The PHP functions var_dump() and print_r() both show information (content) about a variable on screen
  • TIP: wrap the function call in a <pre> tag to preserve the formatting of the output
Last Updated: 9/28/2022, 12:13:29 PM