3

Is there any function which will accomplish the equivalent of array_search with a $needle that is an array? Like, this would be an ideal solution:

$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );

If no function, any other functions that accept needles which may be arrays that I can use to create a custom function?

Jordan
  • 187
  • 3
  • 7

4 Answers4

3

This might help build your function:

$intersection = array_intersect($needle, $haystack);

if ($intersection) // $haystack has at least one of $needle

if (count($intersection) == count($needle)) // $haystack has every needle
Matthew
  • 47,584
  • 11
  • 86
  • 98
2

You can use array_intersect() : http://php.net/manual/en/function.array-intersect.php

if (empty(array_intersect($needle, $haystack)) {
   //nothing from needle exists in haystack
}
JohnP
  • 49,507
  • 13
  • 108
  • 140
1
$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack


function array_needle_array_search($needle, $haystack)
{
        $results = array();
        foreach($needle as $n)
        {
                $p = array_search($n, $haystack);
                if($p)
                    $results[] = $p;
        }
        return ($results)?$results:false;
}

print_r(array_needle_array_search($needle, $haystack));
S L
  • 14,262
  • 17
  • 77
  • 116
0
$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

if(in_array($needle, $haystack)) {
     echo "found";
}
Prakash
  • 6,562
  • 3
  • 25
  • 33