2

What's the most efficient way to search an array element's sub arrays to check the value of a specific key? For example, given the following array, where I want to check both subarrays "msg" value, and if either is populated, return a boolean result:

[TGMN02] => Array
        (
            [2] => Array
                (
                    [id] => 93143
                    [msg] => 
                )

            [3] => Array
                (
                    [id] => 24876
                    [msg] => 
                )
        )

What I have at the moment is simply looping through and checking, which feels quite clunky.

bsod99
  • 1,287
  • 6
  • 16
  • 32
  • http://www.whathaveyoutried.com/ / show us some real code... – ITroubs Mar 21 '13 at 12:36
  • Looping of one form or another is the way to do it... – Michael Berkowski Mar 21 '13 at 12:38
  • Some users marked this as a duplicate, but the "How to search by key=>value in a multidimensional array in PHP" question that it's linked to is a very different type of problem (a deeply nested array, requiring a recursive solution). This question appears to be asking for a simple loop, checking the sub-elements only one level deep. – orrd Jun 18 '15 at 05:24

2 Answers2

0

I don't know about "most" efficient but this won't necessarily have to iterate through the whole array as it breaks the loop on the first value found, so technically more efficient.

 function hasMsg($a){
   foreach($a as $b)
     if(!empty($b['msg'])) return true;
   return false;
 }

Okay... since some meager comments weren't accompanied by alternative suggestions - you could try using some PHP>5.3 - I really can't see how it would be any more efficient though - it must still loop through the array at some level (but I'm not 100% sure on the inner workings of the PHP interpreter - perhaps there is some internal magic that could speed things up), so this is probably purely aesthetic:

$hasMsg = !!(count(array_filter($a,function($b){ return !empty($b['msg']); })));

... if anything less efficient. There's nothing wrong with "looping" through an array - it's a tried and tested language construct that's been around since the dawn of digital time (almost).

Emissary
  • 9,954
  • 8
  • 54
  • 65
  • You're just "looping through and checking". You've recreated the answer that OP already says they have and not answered the question they actually asked. – user229044 Mar 21 '13 at 12:49
  • *"What I have at the moment is simply looping through and checking, which feels quite clunky."* – user229044 Mar 21 '13 at 12:53
  • Regardless of it "feeling clunky", this is as good a solution as exists for this particular problem in PHP. – orrd Jun 18 '15 at 05:28
-1

First write some custom func and then try to use it with array_walk_recursive(array &$input , callable $funcname [, mixed $userdata = NULL ]) function. Php manual.

sean662
  • 696
  • 6
  • 15