Basic: How to check if an array contains an item?

I was trying to check, if a correct form name was passed to a function. Did it at first by iterating over the elementNames of all form documents like so:

Function frmDocExists(frmName As String) As Boolean
  Dim sFrmDocs() As String
  Dim sFrmDoc As String
  Dim bFound As Boolean

  sFrmDocs = ThisDatabaseDocument.FormDocuments.ElementNames
  For Each sFrmDoc In sFrmDocs
    bFound = (sFrmDoc = frmName)
    If bFound Then Exit For
  Next

  frmDocExists = bFound
End Function

But then I noticed that the API already has a method that helps with the specific case:

API method:

Function frmDocExists(frmName As String) As Boolean
  frmDocExists = ThisDatabaseDocument.FormDocuments.hasByName(frmName)
End Function

But the question still stands for arrays in general:

Is there any existing array utility function to check if an array contains an item? Would I have to cast the array into something else first?

Hello,

You could write a routine like → OoBasic find value in an Array

…or use FieldInArray() or FieldInList() functions from Strings module of standard Tools library

Thanks to @JohnSUN for mentioning the Tools library. I guess the Tools library is the closest that comes to builtin utility functions when the function itself is missing in the Basic dialect.

Also thanks to @Ratslinger for pointing out that implementing sorting + binary search might be a good idea in cases like these. Especially useful if the array is a bit bigger and/or already ordered.

Example for using the FieldInArray function (works with unordered and ordered array):

Function frmDocExists(frmName As String) As Boolean
  GlobalScope.BasicLibraries.loadLibrary("Tools")
  Dim aTest() As String
  aTest = ThisDatabaseDocument.FormDocuments.ElementNames
  frmDocExists = Tools.FieldInArray(aTest, UBound(aTest), frmName)
End Function

I’m using the form names array here just as an example so I don’t have to create and populate one.

Be careful with the Tools library. Often, the function parameters of this library are of type integer, not long, as they should be in modern versions of LO.

Oh, should be careful with huge arrays then. I hope the tools are updated from time to time.