Search array keys and return the index of matched key

前端 未结 3 1837
别那么骄傲
别那么骄傲 2021-01-06 08:37

my array looks like this:

[sx1] => Array
        (
            [sx1] => Pain in Hand
            [sx1L] => Location
            [sx1O] => Other T         


        
3条回答
  •  悲&欢浪女
    2021-01-06 08:59

    If you don't want to use any functions and need to loop through the array anyway to search or match on a specific condition (especially usefully if your searches become more complicated), then you could use the below principle to go through the array and find the index of $mykey and put it into a variable $myindex. This code assume your index starts at zero, if you want to start at 1, then initialize $index = 1;.

    $a = array(
        "one" => 1,
        "two" => 2,
        "three" => 3,
        "seventeen" => 17
    );
    
    $index = 0;
    foreach ($a as $k => $v) {
        if ($k == $mykey) {
                $myindex=$index
        }
        $index=$index+1;
    }
    

提交回复
热议问题