1

Given this array and a name (e.g. 'def'), how do I get the containing array, or key?

$all = array(
 '0' => array(
      'name' => 'abc'
      'option' => 1,
    ),
 '1' => array(
      'name' => 'def'
      'option' => 1,
    ),
 '2' => array(
      'name' => 'ghi'
      'option' => 0,
    ),
);

What's the best way to return this array given 'def'?

$single = array(
  'name' => 'def'
  'option' => 1,
);

I could do something like this:

$single = array();
foreach ($all as $key => $value) {
  if ($value['name'] == 'def') {
    $single = $all[$key]; 
  }
}

Or prerender the keys in the array so that it looks like this:

$all = array(
 'abc' => array(
      'name' => 'abc'
      'option' => 1,
    ),
 'def' => array(
      'name' => 'def'
      'option' => 1,
    ),
 'ghi' => array(
      'name' => 'ghi'
      'option' => 0,
    ),
);
$single = $all['def'];

But I'm wondering if there's a shorter php function for that.

1
  • 1
    The foreach method was always the best for such cases (although it would be marginally better if you include a break inside the if block). You can do it in other ways as well, but they will be more verbose, or less clear, or both. Commented Jan 18, 2013 at 1:01

1 Answer 1

4

You could use array_filter:

array_filter($array, function($var){
   return $var["name"] == "def";
});
Sign up to request clarification or add additional context in comments.

2 Comments

But you also need to unwrap the value found, so something like list($single) = array_filter(...) since reset complains if you pass in a temporary (it takes its parameter by reference). That's the best I could come up with as well, but IMHO it's too clever for its own good.
Thanks for the nice ideas! I marked this as the answer because it's the closest to a single function call as possible. Though indeed not sure I'd use it because of readablity and bit complex.

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.