SQL PHP HTML ASP JavaScript articles and free scripts to download

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"
myArray(1)="USA"

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"
myArray(1)="USA"

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"
myArray(1)="USA"
'Added two elements now let us redeclar and add to more elements
ReDim Preserve myArray(3)
myArray(2)="Canada"
myArray(3)="UAE"


For Each item In myArray
Response.Write(item & "<br>")
Next

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.
Google+

Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked



Join Our Email List
Email:  
For Email Newsletters you can trust
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer