Class06 Arrays MIS 3502 Jeremy Shafer Department of MIS Fox School of Business Temple University
Getting Started It’s time for a gentle (re)introduction to arrays. Our objectives Know what an array is. Be able to create an array in PHP (if you need to) and other array basics Types of arrays Associative vs. Numerically Indexed Arrays One dimensional vs. Multi-dimensional Rectangular vs. Jagged How to loop through arrays Debugging tip – use print_r(); Options for the fetchAll method Sorting Arrays
What is an array? An array is a data type that can contain one or more items called elements. Each element stores a value that you can refer to with an index. The length of the array indicates the number of elements that it contains. In short, an array is a structure that allows us to store multiple pieces of similar data.
Creating an array
Arrays can store any data type. Notice that we are using numbers to index our array here. We’d call that a numerically indexed array!
Appending an element to an Array This is still a numerically indexed array! What is the value of $letters[2] ???
Manipulating array contents How to set a value at a specific index $letters = array('a', 'b', 'c', 'd'); // a, b, c, d $letters[0] = 'e'; // e, b, c, d $letters[3] = 'f'; // e, b, c, f How to get values from an array $letters = array('a', 'b', 'c', 'd'); // a, b, c, d $letter1 = $letters[0]; // $letter1 is 'a' $letter2 = $letters[1]; // $letter2 is 'b'
Another option…
Instead of: array(value1,valule2,value3, …) Associative Arrays Instead of: array(value1,valule2,value3, …) You can see that the differences in syntax between working with associative arrays, and a numerically indexed arrays are pretty minor.
More options…
One Dimensional Array
Multidimensional Arrays
Multidimensional Arrays
Using a “for” loop The PHP function count() will return the number of elements in an array. That can be handy for controlling a “for” loop like this one.
Using a “foreach” loop.
A handy function… Let’s try that…
Sorting an array Let’s try this too. What happens when sort() encounters a multidimensional array?
Where do arrays come from?
Some fetchAll options PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0 And.. there are others. But these three you should know. If you want to know more: http://php.net/manual/en/pdostatement.fetch.php
Ok… let’s try a challenge