3

I'm trying to check if the value of a variable is in an array. Having some difficulty. My array is stored it the global.asa.

    Dim aTree(5)
   aTree(0) = "a"
    aTree(1) = "b"
    aTree(2) = "c"
    aTree(3) = "d"
    aTree(4) = "e"
    aTree(5) = "f"
       Application("aTree") = aTree 

The variable I'm trying to check stores some html content

<% If tree = "a" Then %>
     <div class="card bg_white">
            <h1 class="bold small-caps tbrown">my content</h1>
    </div>
<% End If %>

I'm trying to do the check this way

<% tree = Request("tree") 
if in_array(tree, aTree) then %>
You've found it
<% End if %>

I've got this clunky version that works

(tree <> "" and tree <> "a" and tree <> "b" and tree <> "c" and tree <> "d" and tree <> "e" and tree <> "f")

But I'd like a more elegant way of doing it with an array.

Little help. Thanks.

2 Answers 2

11

There's no built-in InArray() function, but it should be simple enough to build your own.

Function InArray(theArray,theValue)
    dim i, fnd
    fnd = False
    For i = 0 to UBound(theArray)
        If theArray(i) = theValue Then
            fnd = True
            Exit For
        End If
    Next
    InArray = fnd
End Function

Modifying this function to return the index of the value instead of just true/false is left as an exercise for the reader. :)

3
  • Liked the "exercise" 👍
    – TheCuBeMan
    Aug 7, 2022 at 6:01
  • @TheCuBeMan: :) Of course, I used to hate it when my math textbooks did that sort of thing.
    – Martha
    Aug 7, 2022 at 16:29
  • well, that's the best way to learn (and remember!), eventually ;-)
    – TheCuBeMan
    Aug 8, 2022 at 6:05
1

This solution is much faster (as it doesn't potentially loop through the whole array) and elegant. It uses the Filter function:

https://www.w3schools.com/asp/func_filter.asp

function arrayIncludes(byval arr, byval value, byval matchCase)

    dim a, compareType

    arrayIncludes = false

    if (matchCase = false) then 
        compareType = 1
        value = lcase(value)
    else
        compareType = 0
    end if

    myFilter = Filter(arr, value, true, compareType)

    for a = 0 to ubound(myFilter)
        if (matchCase = false) then 
            myFilter(a) = lcase(myFilter(a))
        end if

        if (myFilter(a) = value) then 
            arrayIncludes = true
            exit for
        end if
    next

end function

Usage (returns true if element is in array, or false if it is not):

isIncluded = arrayIncludes(arrayToCheck, elementToSearch, true)  ' or false for matching case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.