This chapter describes:
- What Is an Array?
- Array Variable Declaration
- Assigning Values to Array Elements
- Retrieving Values from Array Elements
- Fixed-Size Array Example
- Dynamic-Size Array Example
- "Array" Function and "For Each" Example
- "Erase" Statements
What Is an Array?
Like many other programming languages, Visual Basic support the concept of array as a built-in data structure with the following features:
- An array can be used to store a collection of data elements of the same data type.
- The number of elements in an array can be a fixed number or can be re-adjusted dynamically.
- An array must be associated with a variable for referencing.
- Each element in an array is associated with a unique index number. By default, index number starts from 0.
- A specific element in an array can be referred by the index number.
- A number of built-in functions are provided to work with arrays.
- "For Each" loop statement is provided as an easy way to loop through all elements in an array.
- "Erase" statement is provided as a quick way to remove all values from an array.
Array Variable Declaration
Visual Basic supports a number of ways to declare array variables:
1. Explicit Declaration with Fixed Size - Using "Dim" statement with size included as:
Dim variable_name(upper_bound) [As data_type]
where "upper_bound" is positive integer specifying the upper bound of the element index, and "data_type" is a data type keyword. Array declared in this way has a fixed size (number of elements). By default, the size of an array is the upper bound plus 1, because index starts from 0. This size can not be changed. If "As data_type" is not specified, default data type "Variant" will be used.
2. Explicit Declaration with Dynamic Size - Using "Dim" and "ReDim" statements as shown in the following syntax:
Dim variable_name() [As data_type] ... ReDim [Preserve] variable_name(upper_bound) ...
The "Dim" statement declares an array variable without any upper bound. The "ReDim" statement resets the upper bound to a new value. The optional key word "Preserve" specifies that all old elements must be preserved when resetting the array size. Array declared in this way can be resized at any time.
3. Implicit Declaration with "Array" Function - Using "Array" function as shown in the following syntax:
variable_name = Array(element_1, element_2, ...)
The "Array" function takes a list of values of "Variant" type, and returns a dynamic-size array.
Note that once an array is declared, all elements will have default values based. See other chapter for different default values for different data types.
VB offers some other useful functions and statements for you to work with arrays:
- IsArray(variable_name) - Returns "True" if the specified variable is an array.
- UBound(array_variable) - Returns the upper bound of the specified array.
- LBound(array_variable) - Returns the lower bound of the specified array.
- "For Each" - Loops through all elements in an array.
- "Erase" - Removes all values from an array.
See sections below for details and examples on those functions and statements.
Assigning Values to Array Elements
New values can be assigned to individual elements in an array using assignment statements like this:
array_variable(index) = new_value
where "index" is the index value of an element the array associated with "array_variable", and "new_value" is the new value to be assigned the array element. The data type of the new value must match the array data type.
Retrieving Values from Array Elements
Retrieving values from array elements can done through their indexes like this:
... = ... array_variable(index) ...
VB also offers a special loop statement, "For Each" statement, to retrieve every element in an array like this:
For Each element_variable In array_variable
... = ... element_variable ...
Next
This statement will iterate through every element in the specified array. At each interation, The value of the current element will be copied to the specified temporary variable, "element_variable". The order of iteration is based on element index values from the lower bound to the upper bound.
Fixed-Size Array Example
To show you how fixed size array works, I wrote the following example, array_fixed_size.html:
<html>
<body>
<!-- array_fixed_size.html
Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
document.writeln("")
Dim aWeek(6)
document.writeln("Is aWeek an array? " & IsArray(aWeek))
aWeek(0) = "Sun"
aWeek(4) = "Thu"
aWeek(6) = "Sat"
aWeek(1) = "Mon"
document.writeln("Days in a week:")
For i=LBound(aWeek) To UBound(aWeek)
document.writeln(" " & i & " = " & aWeek(i))
Next
' aWeek(10) = "Abc" 'Error 1: Subscription out of range
' ReDim Preserve aWeek(10) 'Error 2: This array is fixed
</script>
</pre>
</body>
</html>
Here is the output:
Is aWeek an array? True Days in a week: 0 = Sun 1 = Mon 2 = 3 = 4 = Thu 5 = 6 = Sat
Note that there are two errors commented out in the example:
- Error 1 - Array index (subscription) must be in the range of lower bound and upper bound.
- Error 2 - Fixed-size array can not be resized with "ReDim" statements.
Dynamic-Size Array Example
To show you how dynamic-size array works, I wrote the following example, array_dynamic_size.html:
<html>
<body>
<!-- array_dynamic_size.html
Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
document.writeln("")
Dim aYear()
document.writeln("Check 1: Is aYear an array? " & IsArray(aYear))
' aYear(0) = "Jan" 'Error 1: Subscription out of range
' iSize = UBound(aYear)+1 'Error 2: Index out of range
ReDim aYear(5)
document.writeln("Check 2: Is aYear an array? " & IsArray(aYear))
aYear(0) = "Jan"
aYear(1) = "Feb"
aYear(5) = "Jun"
ReDim Preserve aYear(11)
aYear(10) = "Nov"
document.writeln("Months in a year:")
For i=LBound(aYear) To UBound(aYear)
document.writeln(" " & i & " = " & aYear(i))
Next
</script>
</pre>
</body>
</html>
Here is the output:
Check 1: Is aYear an array? True Check 2: Is aYear an array? True Months in a year: 0 = Jan 1 = Feb 2 = 3 = 4 = 5 = Jun 6 = 7 = 8 = 9 = 10 = Nov 11 =
Note that:
- Output message "Check 1" shows that a dynamic-size array is an array event if its size is not set yet.
- Commented out "Error 2" shows that "UBound" can not be used is array's size is not set yet.
"Array" Function and "For Each" Example
To show you how the "Array" function and the "For Each" statement work, I wrote the following example, array_dynamic_size.html:
<html>
<body>
<!-- array_foreach.html
Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
document.writeln("")
' Creating a dynamic array with the "Array" function
aSite = Array("yahoo", "netscape", "microsoft")
document.writeln("Is aSite an array? " & IsArray(aSite))
document.writeln("Lower bound of aPrime = " & LBound(aSite))
document.writeln("Upper bound of aPrime = " & UBound(aSite))
' Resizing the array
ReDim Preserve aSite(8)
aSite(8) = "ibm"
' Updating array elements
For Each sSite In aSite
sSite = sSite & ".com"
Next
' Retrieving array elements
document.writeln("Web sites:")
For Each sSite In aSite
document.writeln(" " & sSite )
Next
</script>
</pre>
</body>
</html>
Here is the output:
Is aSite an array? True
Lower bound of aPrime = 0
Upper bound of aPrime = 2
Web sites:
yahoo
netscape
microsoft
ibm
Noticed anything interesting? The example confirms that:
- Arrays created with the "Array" function are dynamic-size arrays.
- "For Each" statement creates a copy of the current element in the temporary variable. You can not update element values in this way. My "Updating array elements" code block updated only the temporary variable.
"Erase" Statements
It is interesting to know that VB offers a special statement called "Erase" to remove all values in an array:
Erase array_variable
If the specified array is a fixed-size array, it will reset all elements to the default value. If the specified array is a dynamic-size array, it will reset the array to zero size.
To show you how the "Erase" statements work, I wrote the following example, array_erase.html:
<html>
<body>
<!-- array_erase.html
Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
' Setting a fixed-size array
Dim aFixed(1)
aFixed(0) = "Dog"
aFixed(1) = "Cat"
document.writeln("")
document.writeln("Favorite pets:")
For Each sItem In aFixed
document.writeln(" " & sItem )
Next
' Setting a dynamic-size array
aDynamic = Array("Apple", "Orange")
document.writeln("")
document.writeln("Favorite fruits:")
For Each sItem In aDynamic
document.writeln(" " & sItem )
Next
' Erasing arrays
document.writeln("")
document.writeln("Erasing arrays...")
Erase aFixed
Erase aDynamic
' Looking at arrays again
document.writeln("")
document.writeln("Pets left:")
iCount = 0
For Each sItem In aFixed
iCount = iCount + 1
document.writeln(" " & sItem )
Next
document.writeln(" Count = " & iCount)
document.writeln("")
document.writeln("Fruits left:")
iCount = 0
For Each sItem In aDynamic
iCount = iCount + 1
document.writeln(" " & sItem )
Next
document.writeln(" Count = " & iCount)
</script>
</pre>
</body>
</html>
Here is the output:
Favorite pets: Dog Cat Favorite fruits: Apple Orange Erasing arrays... Pets left: Count = 2 Fruits left: Count = 0I don't see any surprises in the output. Do you?
Conclusions
- There two types of arrays: fixed-size array and dynamic-size array.
- "Dim" and "ReDim" specify upper bound of array index, not the size.
- "Array" is a useful function to create a dynamic-size array quickly.
- "For Each" can iterate through an array with a temporary variable to hold a copy of the current element value.
discuss this topic to forum
