phparraysperformancemultidimensional-arrayfilter

Get first level key in a 2d array of the first row with a specified value in any element


What is the best way to get the parent array key from a 2d array when searching for a value anywhere in each row?

For example, I have this array:

array(
    [0] => array(0=> sample, 1=>picture, 2=>frame, 3=>google)
    [1] => array(0=> iphone, 1=>orange, 2=>love, 3=>msn)
    [2] => array(0=> joe, 1=>geee, 2=>panda, 3=>yahoo)
)

I need to search, for example, google and get the parent array key.

The result should be 0.

I used a for loop for this, but I think it will be slow if I have arrays with 700000 rows.


Solution

  • If you have an array with 700,000 rows you are almost certainly doing something wrong... I would first recomend thinking about utilizing a different data store: flat file or some type of DB.

    
    foreach($array as $key => $value) {
        if(in_array('google', $value)) return $key
    }