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.

1
  • you can var_dump(array_column($response,'types')) for get output array this function. Commented Feb 11, 2016 at 13:30

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I also found out, that array_search("whatisearchfor2", array_column(array_column($response, "types"), 0)); is working, too. What is better or more efficient?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.