0

Is there a function like in_array() than can, check conntent inside array of arrays?

I tried:

$day_events = Array();
array_push($day_events,array('aa','bb','cc'));
array_push($day_events,array('aa','bc','cd'));
array_push($day_events,array('ac','bd','ce'));
echo '<br />';
echo in_array('aa',$day_events); // empty
echo '<br />';
foreach ($day_events as &$value) {
    echo in_array('aa',$value); // 11
}

first in_array() which is the kind of function I am looking for (avoiding the loop) gave empty.

Rikard
  • 7,485
  • 11
  • 55
  • 92
  • 1
    The `in_array()` native PHP function simply doesn't support multi-dimensional arrays. – MackieeE Nov 08 '13 at 15:13
  • @MackieeE, ok. Hmmm... is there another function for that or do I have to live with the for loop? – Rikard Nov 08 '13 at 15:13
  • possible duplicate of [in\_array() and multidimensional array](http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array) – dognose Nov 08 '13 at 15:13
  • @Rikard Yes, you would and I really wouldn't be bothered by the nano-seconds of performance as an effect =) – MackieeE Nov 08 '13 at 15:14
  • @Rikard Secondly, if you truly wanted to avoid looping at all, you'd make an separate multi-dimensional array that only ever contained 'aa' in first place at the point of array_pushing. – MackieeE Nov 08 '13 at 15:17

2 Answers2

0

Use this function, as in_array doesn't natively support multi-dimensional arrays:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

In this case you would you use it like this:

echo in_array_r('aa', $day_events) ? 'Found' : 'Not found';

It was taken from this answer: https://stackoverflow.com/a/4128377/2612112.

Community
  • 1
  • 1
federico-t
  • 12,014
  • 19
  • 67
  • 111
0

By the way it is not avoiding first one it is avoiding the last one which has 'ac'. So you get true from first two. Your code works but I am not sure if that is what you want.

Serhat Akay
  • 536
  • 3
  • 10
  • Thanks for your answer. What I want is to check thru the multi-dimensional array. Check all values inside it agains my value. I can do it with for loop and works, but was looking for a function to do this. – Rikard Nov 08 '13 at 15:22