Length of an array in ASP by using UBound function

We can get the length or total number of element in the array by using UBound() function. Note that the index of the first element of the array is 0. So if there are five elements inside an array then the function UBound() will return 4. Here is the code to get the highest index of the array. Note that total element is 1 plus the highest index.
Dim myArray(3) 'Re-Declaring a dynamic array

myArray(0) = "UK"
myArray(1)="USA"
myArray(2)="Canada"
myArray(3)="UAE"
Response.Write ("Total element of the array = " & UBound(myArray) )

for i=0 to uBound(myArray)
Response.Write "<br>" & myArray(i) 
Next 
Here UBound is used to set the maximum looping length to display each element of the array.

Example 2: Calculating Total Number of Elements in a Multi-dimensional Array

In ASP, we can use UBound() and LBound() to find the size of each dimension in a multi-dimensional array:

Dim arr(3, 4) ' A 2D array with 4 rows and 5 columns
Dim total_elements
total_elements = (UBound(arr, 1) - LBound(arr, 1) + 1) * (UBound(arr, 2) - LBound(arr, 2) + 1)
Response.Write("Total elements in the array: " & total_elements)

Example 3: Using a Function to Find Array Size

We can encapsulate the logic to find the array size in a function:

Function ArraySize(arr)
  ArraySize = UBound(arr) - LBound(arr) + 1
End Function

Dim arr(10)
Response.Write("Size of the array is: " & ArraySize(arr))

Example 4: Iterating Through an Array and Displaying Its Size

We can loop through an array and display the size along with each element:

Dim arr(5), i
For i = LBound(arr) To UBound(arr)
    arr(i) = i * 10 ' Assign values
Next

Response.Write("Size of array: " & UBound(arr) - LBound(arr) + 1 & "<br>")

For i = LBound(arr) To UBound(arr)
    Response.Write("Element " & i & " = " & arr(i) & "<br>")
Next

Example 5: Resizing an Array Dynamically Using ReDim

You can dynamically change the size of an array using ReDim:

Dim arr()
ReDim arr(3) ' Set initial size
arr(0) = "A"
arr(1) = "B"
arr(2) = "C"
arr(3) = "D"
Response.Write("Size before resizing: " & UBound(arr) - LBound(arr) + 1 & "<br>")

ReDim Preserve arr(5) ' Resize and preserve existing values
arr(4) = "E"
arr(5) = "F"
Response.Write("Size after resizing: " & UBound(arr) - LBound(arr) + 1 & "<br>")


In PHP array length or size is found out by using sizeof function
ASP Home

plus2net.com





We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer