object script array => size - element scount

Answers

If you want to count (or otherwise traverse) all the elements in a multidimensional array, you can use $Query - here's a sample with method that does that:

ClassMethod Run()
{
    Set a(1) = "blue"
    Set a(1,3,5,2) = "navy"
    Set a(2) = "red"
    Set a(2,2) = "crimson"
    Set a(3) = "yellow"
    
    Write ..Count(.a)
}

ClassMethod Count(ByRef pArray) As %Integer [ PublicList = pArray ]
{
    Set count = 0
    Set ref = $Query(pArray(""))
    While (ref '= "") {
        Set count = count + 1
        Set ref = $Query(@ref)
    }
    Quit count
}

If you're sure that all your keys are consecutive integers, then use $order to get the last element, which would also be a count of them:

write $order(a(""),-1)

Also there is a common approach to use the root as a counter of the one-level array using $seq(uence) or $I(ncrement). E.g.

Class Test.Arrays {

ClassMethod ArrayExample()

{

 set a($seq(a))="blue"

set a($seq(a))="red"

set a($seq(a))="yellow"

write a,!    // will return 3

zwrite a // will out the full array to the device

}

}

And if we execute the following in terminal you'll get:

USER>d ##class(Test.Arrays).ArrayExample()

3

a=3
a(1)="blue"
a(2)="red"
a(3)="yellow"

Also see the good article on $seq vs $I by @Alexander Koblov

HTH

Comments