Author Topic: [Solved] Given a value in an array, find its index  (Read 548 times)

I have an array like $myArray = [44, 45, 77, 99].

I have an array like:
$myArray[1] = 44;
$myArray[2] = 45;
$myArray[3] = 77;

I need to get the index of the value 77.

I'm looking for something along the lines of $myArray.indexOf(77);
I'd like to avoid a for loop to search through all the values, unless it's the only way.
« Last Edit: June 21, 2016, 04:03:48 PM by Farad »

The first step is to believe that it's not actually an array.

$myArray[0] = 44; is really just $myArray0 = 44;
Therefore, you cannot call functions on it, nor can you define them as $myArray = [44, 45, 77, 99];

If you know there won't be any duplicates in the given array, you could do something like this.
$myArrayIdx[%value]

For example,

$myArray[0] = 44;
$myArrayIdx[44] = 0;
$myArray[1] = 45;
$myArrayIdx[45] = 1;
$myArray[2] = 77;
$myArrayIdx[77] = 2;
$myArray[3] = 99;
$myArrayIdx[99] = 3;

But other than that, I don't believe there is any good way to do this.

If you know there won't be any duplicates in the given array, you could do something like this.
$myArrayIdx[%value]

For example,

$myArray[0] = 44;
$myArrayIdx[44] = 0;
$myArray[1] = 45;
$myArrayIdx[45] = 1;
$myArray[2] = 77;
$myArrayIdx[77] = 2;
$myArray[3] = 99;
$myArrayIdx[99] = 3;

But other than that, I don't believe there is any good way to do this.

That will work great, thanks.

Another way would be to loop through the array until you find the value (assuming there are no duplicates)

Edit: oops, in after OP Edited his post I guess.

Another way would be to loop through the array until you find the value (assuming there are no duplicates)

Edit: oops, in after OP Edited his post I guess.
All he did was strikeout the initial array, and add in the new one.

Yeah, I noticed I just didn't catch it I guess.