Arrays can help you to create more sophisticated scripts, by storing multiple values within a single variable.
What is an array?
Arrays are a fundamental part of most programming languages and scripting languages. Arrays are simply an ordered stack of data items with the same data type. Using arrays, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.
For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:
This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do stuff like loop through all your variables. That's where arrays come into play. You could put all your questions into one array.
Arrays can be visualized as a stack of elements.
|2||What are two dimensional arrays?|
then by assigning values to the array...
So, using our prior example, we could write:
You can access an array element by referring to the name of the array and the element's index number.
Displaying Array Elements
Modifying the Contents of an Array
You can modify the contents of an array by specifying a value for a given index number:
In this case, the value of the second element of this array would now be How to modify an array?
Two Dimensional Arrays
So far we've only discussed one dimensional arrays. You can also create two dimensional arrays, which can be much more powerful than one dimensional arrays. Two dimensional arrays are covered in the next lesson.