vmg
vmg

Reputation: 10566

Loop over all items in any-dimensional array in VBScript

I need to iterate over all elements in array in VBScript, but it's dimensions are unknown. How I can do that?

In Java, for example, multi-dimensional array is array of arrays, and you can subarray. I don't know how I can that in VBscript.

Any help is appreciated.

Update: This task can be resolved by using For Each loop against array. So, what stands beyond For Each loop? How it implemented?

Upvotes: 1

Views: 5324

Answers (1)

stealthyninja
stealthyninja

Reputation: 10371

You can create a Function or Sub to recursively check if keys within an array are also arrays. Here's some sample code to demonstrate:

<%
' Simple sub to just loop through the array and echo its values
Sub array_values(array_value)
    Dim i

    If IsArray(array_value) Then
        For i = LBound(array_value) To UBound(array_value)
            If IsArray(array_value(i)) Then
                array_values array_value(i)
            Else
                Response.Write array_value(i) & "<br>"
            End If
        Next
    End If
End Sub


' Sample array
Dim a

a = array( _
    array("1", "2", "3"), _
    array("a", "b", "c", _
        array("e", "f", "g", _
            array("h", "i", "j", _
                array("k", "l", "m", _
                    array("n", "o", "p", _
                        array("q", "r", "s", _
                            array("t", "u", "v", _
                                array("w", "x", "y") _
                            ) _
                        ) _
                    ) _
                ) _
            ) _
        ) _
    ) _
)

array_values a
%>

Upvotes: 2

Related Questions