1 <?php
2 echo "Some examples of using arrays, in php.\n\n";
3
4 echo "----------------------\n";
5 echo "Using arrays w/ numeric indices.\n\n";
6
7 $arr = array("john","mary","zimbo");
8 echo "index 1 contains ", $arr[1], "\n"; // "mary"
9
10 $arr[] = "betty"; // Insert at the *next* location.
11 echo "index 3 contains ", $arr[3], "\n"; // "betty"
12
13 $arr[23] = "justine";
14 echo "index 17 contains ", $arr[17], "\n"; // NULL
15 echo "index 23 contains ", $arr[23], "\n"; // "justine"
16
17 $arr[] = "rachel"; // Wait, what counts as the *next* location now? 24, not 4 (!).
18 echo "index 4 contains ", $arr[ 4], "<br />\n"; // NULL
19 echo "index 24 contains ", $arr[24], "<br />\n"; // "rachel"
20
21
22 echo "----------------------\n";
23 echo "Using arrays w/ string indices.\n\n";
24
25 $crsarr = array("web"=>325, "java1"=>120);
26
27 echo "index 'web' contains ", $crsarr['web'], "\n"; // 325
28
29 echo "But watch out, when doing variable-substitution with arrays:";
30 echo "index 'web' contains ", $crsarr['web'], "\n"; // 325
31 $fave = 'web';
32 echo "index '$fave' contains ", $crsarr[$fave], "\n"; // 325
33
34 $crsarr["discretemath"] = 122;
35 echo 'index "discretemath" contains ', $crsarr['discretemath'], "\n"; // 122
36
37 // The array("john","mary","zimbo") is the same as:
38 $arr = array(0 => "john", 1 => "mary", 2 => "zimbo");
39
40
41 /*****************************************/
42 echo "(Reached here, 2013.Feb.06.)\n";
43
44 echo "----------------------\n";
45 echo "Looping over arrays\n\n";
46
47 /* Looping over arrays: */
48
49 function sumLengths( $data ) {
50 $lenSoFar = 0; // Include this, even if not strictly necessary!
51 foreach($arr AS $x) {
52 $lenSoFar += strlen($x);
53 }
54 return $lenSoFar;
55 }
56
57
58 /* Sometimes we need to know the index, as well as the value: */
59
60 function myArrayToString( $data ) {
61 $stuffSoFar = "";
62 foreach($data AS $key => $val) {
63 $stuffSoFar .= "$key maps to $val.\n";
64 }
65 return "Array {\n" . $stuffSoFar . "}\n";
66 }
67
68 require_once( "../Homeworks/hw02/utils.php" );
69
70 test(
71 myArrayToString(
72 array( "en" => "hi", "fr" => "bonjour", "de" => "'tag" )
73 ),
74
75 "Array {
76 en maps to hi.
77 fr maps to bonjour.
78 de maps to 'tag.
79 }" );
80
81 echo "<pre>", myArrayToString( $crsarr ), "</pre>\n";
82
83
84 echo "----------------------\n";
85 echo "Printing arrays\n\n";
86
87 print_r( $crsarr );
88 print_r( array(20, 21, "howdy" => "bye", "aloha" => "sayonara", 2 => 22 ) );
89
90 /* Of course, if printing the array-contents as html, the browser ignores newlines
91 (well, technically it treats all whitespace as a single space char).
92 The usual 'solution' is to print it inside a `pre` tag.
93 This is for q&d debugging, as the output is meant for programmers, not end-users.
94 */
95 echo "<pre>\n";
96 print_r( $crsarr );
97 echo "<pre />\n";
98
99
100 echo "<hr />\n";
101 show_source('lect02b-arrays.php'); // This file.
102
103 ?> |