Finding a value within an array

New to Gambas? Post your questions here. No question is too silly or too simple.
Post Reply
PartierSP
Posts: 57
Joined: Tuesday 30th November 2021 12:14am
Location: Canada
Contact:

Finding a value within an array

Post 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).
User avatar
cogier
Site Admin
Posts: 1118
Joined: Wednesday 21st September 2016 2:22pm
Location: Guernsey, Channel Islands

Re: Finding a value within an array

Post 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.
PartierSP
Posts: 57
Joined: Tuesday 30th November 2021 12:14am
Location: Canada
Contact:

Re: Finding a value within an array

Post 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.
User avatar
thatbruce
Posts: 161
Joined: Saturday 4th September 2021 11:29pm

Re: Finding a value within an array

Post by thatbruce »

Because not all Arrays have searchable contents, for example Object[]
Have you ever noticed that software is never advertised using the adjective "spreadable".
Post Reply