ITM 352 Simple Arrays
Arrays Collections Array basics Declaration, allocation, and initialization Subscripting Processing arrays by iteration and recursion Reading and writing arrays
Collections Sometimes you need to manage multiple pieces of data as a group of things rather than individual values. A collection is a compound data type that contains multiple values to do just this. We have already seen a kind of collection: strings (a collection of characters). the operation $aString[5] returns the 6th character (counting from zero).
Order: Index vs. Association Strings could be used to create another type of collection, lists (like a list you might create on paper for groceries). $groceries = “Item 1: Eggs, Item 2: Milk, Item 3: Spam" Both are ordered but the particular sequence may or may not be important. Strings: sequence of characters. Order is important Grocery List: collection of items. Order is unimportant Task List: sequence of tasks. Order is important
Order: Index vs. Association (cont.) When a collection must have a particular sequence, its values are indexed by position number Strings: $name = "Fred", $name[0] = 'F', $name[1] = 'r', $name[2] = 'e', … When a collection doesn't have a particular sequence, its values are associated by keys Grocery List: Value for key 'Item 3' is 'Spam'
Why Not Variable Variables? $product1 = "Phone"; $product2 = "Candy"; $product3 = "Soda"; for($i=1; $i<=3; $i++) { $ident = "product$i"; print $$ident . "<BR>"; } This is sort of a collection, but not terribly convenient or efficient. Why?
Arrays A general kind of ordered collection. Special features: Built-in to PHP, has special syntax. Elements can be any type of data (including other arrays!) Collection can change size anytime Arrays may indexed or associative (or both!) Note: All arrays in PHP are associative Keys are automatically set to integers if you don’t specify them
Arrays (cont.) Definition: An array is a named collection of values $indexedArray value 'green' 'blue' 'yellow' 'purple' 'red' element position (identified by index) 1 2 3 4
Arrays (cont.) Definition: The values can be of different types. $indexedArray value 17 'Hi' 9.33 NULL true element position (identified by index) 4 1 2 3 $associativeArray value 17 'Hi' 9.33 NULL true element position (identified by key) 'age' 'greet' 'amount' 'notset' 'is_easy'
Array Terminology (indexed) Array name $temperature[2] $temperature[$2] $temperature[2] = 32; Index - also called a subscript or index - must be an int, - or an expression that evaluates to an int Indexed variable - also called an element or subscripted variable Value of the indexed variable; also called an element of the array
Array Terminology (associative) Array name $product['price'] $product['price'] = 32; key - also called a subscript or index - must be an int, - or an expression that evaluates to an int keyed variable - also called an element or subscripted variable Value of the indexed variable; also called an element of the array
Subscripting Principal feature of arrays: ability to access each element easily. Use notation to access elements of an array. If the key-expression has integer value n, this returns the n'th element in array-name, counting from zero (!) If the key-expression is a string, it returns the value associated with that key array-name[key-expression]
Subscripting Examples $grades[0] = 75; echo $grades[0]; $i = 2; $clocks[$i-1] = time(); $clocks[] = time()+1; printf("<BR>time[1] is %s and time[2] is %s", $clocks[$i-1], $clocks[2]); $name['first'] = "Rumple"; $name['last'] = "Stilskin"; echo "<BR>name is {$name['first']} {$name['last']}"; $thingy[] = 1; $thingy[] = 4; echo "<BR> $thingy[0] and $thingy[1]"; This is how you add elements to an existing indexed array.
Subscript Errors Using a subscript larger than length-1 or less than 0 or a key that does not exist will not cause the program to stop executing. No element will be returned Take care to use the correct subscripts! Be careful of interpolation problems when accessing array elements within a string echo "The product is $product['name']"; // won't work! echo "The product is $product[name]"; echo "The product is {$product['name']}";
Declaring and Initializing arrays One method: initialization list using array(). This allocates the array as a 3-element array and initializes its elements the same as: $angles[0] = 3.5; $angles[1] = 9.7; $angles[2] = 15.01; Key-value pairs can also be used $angles = array(3.5, 9.7, 15.01); $product = array('name' => 'gumball', 'price' => 0.07, 'quantity' => 1500);
Finding the Length of an Array Size of $anArray can be determined using count($anArray) or sizeof($anArray). This is useful when using an array of unknown size in a loop: $counter=0; while( $counter < sizeof($anArray) ) { echo "element $counter is {$anArray[$counter]}"; $counter++; } How big is $anArray? We don’t need to know! Just use count($anArray)or sizeof($anArray).
Using sizeof() $colors[] = "red"; // Set up the array $colors[] = "blue"; $colors[] = "purple"; $colors[] = "yellow"; $count=0; // Initialize array counter while( $count < sizeof($colors) ) { // Print out each array index and value echo "Color $counter is {$colors[$count]}<BR>"; $count++; }
Generating HTML with Loops <?php $users = array('Jason', 'Phil', 'Herbert', 'Anil'); echo '<center>'; echo '<table border = 2 >'; echo '<th>Number</th><th>Username</th>'; for ($i = 0; $i < count($users); $i++) { echo '<tr>'; echo "<td>$i</td>"; echo "<td>$users[$i]</td>"; echo '</tr>'; } echo '</table>'; ?>