2

I am aware of this question, but I have an additional one to search for an array-key. Take a look at this:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(6) "Text 1"
    ["types"]=>
    array(3) {
      [0]=>
      string(7) "Level 1"
      [1]=>
      string(14) "something else"
      [2]=>
      string(15) "whatisearchfor1"
    }
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(6) "Text 2"
    ["types"]=>
    array(3) {
      [0]=>
      string(7) "Level 2"
      [1]=>
      string(14) "something else"
      [2]=>
      string(15) "whatisearchfor2"
    }
  }
}

This snippet...

echo array_search("Text 2", array_column($response, "name"));

...gives me a 1 for the second array-key, in which the term was found.

But how do I receive the global array-key (0 or 1), if I search for whatisearchfor2, which is stored in the multi-array "types"?

echo array_search("whatisearchfor2", array_column($response, "types"));

...doesn't work.

Sebastian
  • 625
  • 9
  • 22

1 Answers1

2

In your case array_column($response, "types") will return an array of arrays. But to get "global array-key (0 or 1), if you search for whatisearchfor2" use the following approach with array_walk:

$key = null; // will contain the needed 'global array-key' if a search was successful
$needle = "whatisearchfor2"; // searched word

// assuming that $arr is your initial array
array_walk($arr, function ($v,$k) use(&$key, $needle){
    if (in_array($needle, $v['types'])){
        $key = $k;
    }
});

var_dump($key);    // outputs: int(1)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • I also found out, that `array_search("whatisearchfor2", array_column(array_column($response, "types"), 0));` is working, too. What is better or more efficient? – Sebastian Feb 12 '16 at 15:16