Declaring array in ASP

We have seen how to declare variables in VBScript used in ASP. Now we will try to learn how we can declare and use arrays inside ASP code. Let us try using declare one array with fixed number of elements.

Dim myArray(1) 
The above line declared a fixed width array. Now we will try to add element to this array.

myArray(0) = "UK"
You can see we have added two elements to this array. As the array starts with 0 element so we can add 2 elements if it is declared like this. Same way myArray(5) can store 6 elements , starting from 0 element.

What happens if we try to add one more element to the above array? We will get error message as we declared the myArray element as fixed number array. To change the number of elements to be stored , we have to declare the array as dynamic size array. But before adding the element we must re-declare the size of the array. Here is the code to declare a dynamic size array.

Dim myArray() 'Declaring a dynamic array
ReDim myArray(1) 'Re Declaring a dynamic array
myArray(0) = "UK"
You can see we have re-declared the array with size and then stored elements inside it. Now as we declared this element at the starting as a dynamic array we can re-declare this array with any size. If we are not declaring as dynamic array then we can't change the size by re-declaring the array. The code below will generate error.

Dim myArray(1) 'Declaring a fixed array
ReDim myArray(2) 'Re Declaring the fixed array
Now let us work with adding more elements to an dynamic array. Here we will first declare a dynamic array and then add two elements to it by re-declaring the size of the array. Then we will try to add two more elements to the same array by preserving the old elements. To add more elements we have to use preserve while re-declaring the array like below.

Dim myArray() 'Declaring a dynamic array
ReDim myArray(1) 'Re-Declaring a dynamic array

myArray(0) = "UK"
'Added two elements now let us redeclar and add to more elements
ReDim Preserve myArray(3)

For Each item In myArray
Response.Write(item & "<br>")
We have included the for each loop to display all the element of the array. The output will display all four elements we added now.

Be the first to post comment on this article :


Post Comment This is for short comments only. Use the forum for more discussions.

HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2016 All rights reserved worldwide Privacy Policy Disclaimer