Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search array keys and return the index of matched key

Tags:

arrays

php

my array looks like this:

[sx1] => Array
        (
            [sx1] => Pain in Hand
            [sx1L] => Location
            [sx1O] => Other Treat
            [sx1T] => Type
            [sx1R] => Radiation
            [sx1A] => Aggrivate Ease
            [sx1D] => Duration
            [sx1I] => Irit
            [sx1P] => Previous Hx
            [SX1T_1] => CX
            [SX1T_2] => Shld
            [SX1T_3] => Trnk
            [SX1T_4] => Hip
            [SX1T_5] => 
        )

I need to be able to search the array by a key, and then return the index of the matched item. For example, I need to search the array for the key "SX1T_1" and then return the index of that item in the array.

Thanks for any help.

like image 966
Emmanuel Avatar asked Dec 05 '22 01:12

Emmanuel


1 Answers

You can use array_search on the array keys (array_keys) to get the numerical index:

$array = array(
    'sx1' => 'Pain in Hand',
    'sx1L' => 'Location',
    'sx1O' => 'Other Treat',
    'sx1T' => 'Type',
    'sx1R' => 'Radiation',
    'sx1A' => 'Aggrivate Ease',
    'sx1D' => 'Duration',
    'sx1I' => 'Irit',
    'sx1P' => 'Previous Hx',
    'SX1T_1' => 'CX',
    'SX1T_2' => 'Shld',
    'SX1T_3' => 'Trnk',
    'SX1T_4' => 'Hip',
    'SX1T_5' => '',
);
var_dump(array_search('SX1T_1', array_keys($array)));  // int(9)
like image 72
Gumbo Avatar answered Dec 31 '22 18:12

Gumbo