11.07.2015 Views

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

PHP MySQL - Stilson.net

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

www.it-ebooks.infoCHAPTER 5 • ARRAYSCreating an ArrayUnlike other languages, <strong>PHP</strong> doesn’t require that you assign a size to an array at creation time. In fact,because it’s a loosely typed language, <strong>PHP</strong> doesn’t even require that you declare the array before using it,although you’re free to do so. Each approach is introduced in this section, beginning with the informalvariety.Individual elements of a <strong>PHP</strong> array are referenced by denoting the element between a pair of squarebrackets. Because there is no size limitation on the array, you can create the array simply by makingreference to it, like this:$state[0] = "Delaware";You can then display the first element of the array $state, like this:echo $state[0];Additional values can be added by mapping each new value to an array index, like this:$state[1] = "Pennsylvania";$state[2] = "New Jersey";...$state[49] = "Hawaii";Interestingly, if you intend for the index value to be numerical and ascending, you can omit theindex value at creation time:$state[] = "Pennsylvania";$state[] = "New Jersey";...$state[] = "Hawaii";Creating associative arrays in this fashion is equally trivial except that the key is always required.The following example creates an array that matches U.S. state names with their date of entry into theUnion:$state["Delaware"] = "December 7, 1787";$state["Pennsylvania"] = "December 12, 1787";$state["New Jersey"] = "December 18, 1787";...$state["Hawaii"] = "August 21, 1959";The array() construct, discussed next, is a functionally identical yet somewhat more formal meansfor creating arrays.Creating Arrays with array()The array() construct takes as its input zero or more items and returns an array consisting of theseinput elements. Its prototype looks like this:105

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!