Shehryar Khalid
Shehryar Khalid

Reputation: 31

find array's elements are in another array in PHP

Array A:

486 987

Array B:

247-16-02-2009 486-16-02-2009 562-16-02-2009 1257-16-02-2009 486-16-02-2009 

I want to search and list all Array A elements that matches in Array B. for example: 486-16-02-2009 (twice).

Upvotes: 1

Views: 94

Answers (4)

AbraCadaver
AbraCadaver

Reputation: 78994

You can use a regex by imploding $arrayA into a pattern. This will find $arrayA items anywhere in $arrayB items:

$pattern = implode("|", $arrayA);
$result  = preg_grep("/$pattern/", $arrayB);

To match only at the start of $arrayB items use the ^ anchor "/^$pattern/".

You may want to run $arrayA elements through preg_quote() if there may be special pattern characters there.

Upvotes: 3

Spencer D
Spencer D

Reputation: 3486

Somewhat similar to two of the other answers, but this would be my approach:

$matches = array(); // We'll store the matches in this array

// Loop through all values we are searching for
foreach($arrayA as $needle){
    // Loop through all values we are looking within
    foreach($arrayB as $haystack){
        if(strpos($needle, $haystack) !== false){
            // We found a match.
            // Let's make sure we do not add the match to the array twice (de-duplication):
            if(!in_array($haystack, $needle, true)){
                // This match does not already exist in our array of matches
                // Push it into the matches array
                array_push($matches, $haystack);
            }
        }
    }
}

Note: This solution uses in_array() to prevent match duplication. If you would like matches that match more than one value to show up more than once, then simply remove the if-statement that has !in_array(...) as its conditional.

Upvotes: 0

Carlos Gant
Carlos Gant

Reputation: 732

You must walk the two arrays searching for each case:

Working example: http://ideone.com/pDCZ1R

<?php


$needle = [486, 987];
$haystack = ["247-16-02-2009", "486-16-02-2009", "562-16-02-2009", "1257-16-02-2009", "486-16-02-2009"];

$result = array_filter($haystack, function($item) use ($needle){
    foreach($needle as $v){
        if(strpos($item, strval($v)) !== false){
            return true;
        }
    }
    return false;
});

print_r($result);

Upvotes: 1

Lando
Lando

Reputation: 417

You could do something like this, however it's probably not as good as using php built-ins like array-intersect because we're entering loop-hell. If either array gets too big your script will slow to a crawl.

foreach ($arrB as $values) {
    foreach ($arrA as $compare) {
        if (substr($values, 0, strlen($compare)) == $compare) {
            //do stuff
        }
    }
}

Upvotes: 2

Related Questions