Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

5 Answers

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
share|improve this answer

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
}
share|improve this answer
$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));
share|improve this answer
$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

if(in_array($needle, $haystack)) {
     echo "found";
}
share|improve this answer

From Javascript equivalent of PHP's in_array():

in_array function

a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}
if (in_array('o', $a)) {
    echo "'o' was found\n";
}
share|improve this answer
1  
If you copy stuff from other answers, please add attribution. Taken from stackoverflow.com/questions/784012/… – Pekka 웃 Apr 16 '11 at 12:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.