Ajay Kadyan
Ajay Kadyan

Reputation: 1079

How to find Position of index in an array in php

I have an array like this

Array
(
[33] => 
[53] => 
[82] => 
[36] => 
[47] => 
[42] => 
[1] => 
[12] => 
[86] => 
[68] => 
[31] => 1.00
[2] => 1.00
[87] => 2.00
[50] => 3.00
[10] => 3.00
[55] => 3.00
[48] => 3.00
[70] => 3.00
[90] => 3.00
[37] => 3.00
[69] => 3.00
[8] => 3.00
[49] => 3.00
[26] => 3.00
[13] => 3.00
[61] => 3.00
[59] => 3.00
[73] => 4.00
[64] => 4.00
[77] => 4.00
[78] => 4.00
[65] => 4.00
[66] => 4.00
[63] => 4.00
[76] => 4.00
[51] => 4.00
[52] => 4.00
[43] => 4.00
[58] => 4.00
[60] => 4.00
[74] => 4.00
[67] => 4.00
[35] => 4.00
[17] => 4.00
[16] => 4.00
[18] => 4.00
[20] => 4.00
[41] => 4.00
[15] => 4.00
[11] => 4.00
[4] => 4.00
[5] => 4.00
[6] => 4.00
[7] => 4.00
[83] => 4.00
[22] => 4.00
[34] => 4.00
[38] => 4.00
[40] => 4.00
[25] => 4.00
[32] => 4.00
[80] => 4.00
[81] => 4.00
[27] => 4.00
[30] => 4.00
[79] => 5.00
[89] => 5.00
[88] => 5.00
[72] => 5.00
[71] => 5.00
[44] => 5.00
[21] => 5.00
[23] => 5.00
[24] => 5.00
[19] => 5.00
[14] => 5.00
[3] => 5.00
[9] => 5.00
[28] => 5.00
[29] => 5.00
[56] => 5.00
[57] => 5.00
[54] => 5.00
[46] => 5.00
[39] => 5.00
[45] => 5.00
[62] => 5.00
)

Now what I want to find position of particular index. i.e if I search 53 then it returns its position i.e. 2. As I'm considering 53 at SECOND position.

Upvotes: 0

Views: 213

Answers (4)

Hilmi
Hilmi

Reputation: 3439

you can use

$a = array_keys($array)

to get an array that its values is the $array => keys

after that you can use

$a = array_flip($a);

to make the array values are the indexes of the array (positions as you want!)

then

$a["53"];//for example will get what you want 

hope it helps

Note : if you are frequently accessing the $a use my way because it build the array and after that you'll have O(1) access time, if you need it for one or two access its better to use array_search to get the index from the array_keys array with O(n).

Upvotes: 4

Kani
Kani

Reputation: 840

Get the keys with array_keys() and then try array_search() to get the index of it.

$keys = array_keys($yourArray);
$key = array_search('53', $keys);

didnt tested it but should work.

Upvotes: 5

xdazz
xdazz

Reputation: 160833

function findIndex($arr, $needle) {
    $i = 0;
    foreach ($arr as $key => $value) {
      if ($key === $needle) {
         return $i;
      }
      $i++;
    }
    return false;
}

Upvotes: 2

Najzero
Najzero

Reputation: 3202

Get all array-keys via array_keys() function and extract your desired key value then. see http://www.php.net/manual/en/function.array-keys.php

Upvotes: 1

Related Questions