Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index number of a key in PHP?

Tags:

arrays

php

I have an array in PHP as the following:

[0] => Array
    (
        [41] => 20
        [2] => 42
        [3] => 30
        [12] => 94
        [32] => -2
        [39] => -3
        [40] => -15
    )

I just want to fetch the index number of a particular key, like the index number of the key 41 is 0, index number of the key: 2 is 1, and so on. So please tell me how to do it in PHP. Thanks

like image 891
Naved Ahmed Avatar asked Sep 13 '25 05:09

Naved Ahmed


1 Answers

Quick way

$number = array_search($index, array_keys($array));

Long way

$i = 0;
$number = false;
foreach ($array as $key => $value){
if ($key == $index){
    $number = $i;
    break;}
$i++;
}
like image 152
sectus Avatar answered Sep 14 '25 17:09

sectus