Page 1 of 1

Finding a value within an array

Posted: Sunday 5th March 2023 9:40am
by PartierSP
If I had an array with various integer values and wanted to find what index value contains a given search value, is there a command to do that, or do I simply have to write a little search function?

For example. If I had the following array:
Dim ar As Integer[]
ar=array(5,6,4,7,3,8,2,9,1,0)

and I was looking for 3, I would want a function to return the value 4.
Or, if I was looking for 6, I'd want it to return the value 1.

Is there a built in function that can do this, or do I have to write a simple FOR EACH loop and do it manually. I know in some languages like PHP they have such functions array_search($needle, $haystack).

Re: Finding a value within an array

Posted: Sunday 5th March 2023 11:18am
by cogier
There is an easy way to do this: -

Public Sub Form_Open()

  Dim ar As Integer[] = [5, 6, 4, 7, 3, 8, 2, 9, 1, 0]

  Print ar.Find(3)  ''Result = 4
  Print ar.Find(6)  ''Result = 1

End


There is a lot you can do with arrays. Have a look ]here.

Re: Finding a value within an array

Posted: Monday 6th March 2023 12:43am
by PartierSP
Perfect! That's exactly what I was looking for. Just I'm kinda surprised that it was listed in the help under Integer[] and not under Array. No wonder I didn't find it.

Re: Finding a value within an array

Posted: Tuesday 7th March 2023 9:08am
by thatbruce
Because not all Arrays have searchable contents, for example Object[]