PHP offers one more type of loop, the "foreach" loop, which is designed specifically for use with array variables. Logic would suggest that we explain array variables before we attempt to teach you the "foreach" loop...and you know what slaves we are to logic! Thus far, the variables you've used contain only a single value - for example, However, array variables are a different kettle of fish altogether. An array variable can best be thought of as a "container" variable, which can contain one or more values. For example, Here, $desserts is an array variable, which contains the values "chocolate mousse", "tiramisu", "apple pie", and "chocolate fudge cake". Array variables are particularly useful for grouping related values together - names, dates, phone numbers of ex-girlfriends et al. The various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the element you would use the notation while would be - essentially, the array variable name followed by the index number enclosed within square braces. Geeks refer to this as "zero-based indexing". Defining an array variable is simple via the array() function - here's how: The rules for choosing an array variable name are the same as those for any other PHP variable - it must begin with a letter, and can optionally be followed by more letters and numbers. Alternatively, you can define an array by specifying values for each element in the index notation, like this:
blog comments powered by Disqus |