So now we’re going to get into what I consider the most important thing in order to be productive with programming: loops & arrays. I remember when I was first learning programming, I basically got the concept of loops, but I really didn’t get their importance. I certainly didn’t understand precisely how important it would be. It wasn’t until I got to object oriented programming where I really fell in love with the value of loops and arrays, specifically when looping through objects of the same type, and performing similar actions on the objects. Talking about objects is a little bit too advanced for what I’m trying to convey right now. Just put it into the back of your mind that we will in a later tutorial deal specifically with looping through arrays of objects, and the results will be so extraordinarily useful, and appear in almost every web page you make.
Ok, so before we can get to loops you need to understand arrays. I’ve always wondered why every explanation I’ve read of what an array is didn’t start by describing the definition of an “array” in plain English unrelated to programming. Either way, that’s how I’ll start. Without even looking up the precise definition of “array” in a dictionary, I’m going to describe it in a way I think everyone thinks about it, and I’m going to do so with an example: you buy a box of Crayola crayons and dump them all out on a table, you now have an array of crayons to choose from. You have more than one or many crayons. The connotation I usually think of when thinking of “array” is a bunch of items, specifically where they’re all not the same.
In programming an array is a list of items. So simply we have a variable called $anything. The idea is that this variable holds a laundry list of items. So rather than $anything equaling 1, it equals a list of values, such as 7, 4, 8, 9, 10. That only leaves one final thing to understand, which is simply the syntax with which these values are stored under the heading of this single $anything variable. In order to demonstrate how multiple values are stored under a single heading, i.e. within a variable of a single name such as $anything, I’ll provide an example:
So that means you can get the value of one of these items like this:
The result is that 9 is displayed in the web browser. The number 3 in this case is called the “key” and 9 is the “value.” So basically you can access any values in the list by using the key. Just while we’re at it, I’ll point out that this array could have been built like this: