Burndog
Burndog

Reputation: 719

Search array for multiple strings?

I’m searching for IF a string matching the email domains is present in a recordset.

$outsideService is our array of needles to look for:

$outsideService = array('guest.booking.com','vrbo.com'); // Add outside services to screen for not having emails in DB

My recordset array is $OS as created below:

$OS = ($Departing->Results); // Gather recordset  array

From that array I create a new array with just the email col:

$DepartingOS = array_column($OS, 'email'); // [index, value]

Result (haystack):

 Array
 (
     [0] => [email protected]
     [1] => [email protected]
     [2] => 0
 )

So now I need to compare to see IF the needle is in the haystack :

 if(preg_match($outsideService, $DepartingOS)) {
    echo ’True’;
}

This did not work. I believe the problem is preg_match does not work with an array as the haystack? Meaning I would need to loop the array looking for the needle each time.

But I also tried this method where the needles are set manually and still no luck.

if(preg_match('(guest.booking.com|vrbo.com)', $DepartingOS)===1) {
echo 'True';
}

Am I using preg_match wrong? How would I search the recordset array for the needles?

Upvotes: 0

Views: 58

Answers (1)

Nick
Nick

Reputation: 147166

What you really need to do is iterate each of your arrays, checking whether any value of $outsideService is located within a value inside $DepartingOS. You can do this with a nested array_reduce, using strpos to check for a match:

$outsideService = array('guest.booking.com','vrbo.com');
$DepartingOS = array('[email protected]', '[email protected]', '0');

if (array_reduce($outsideService, function ($c, $OS) use ($DepartingOS) {
    return $c || array_reduce($DepartingOS, function ($c, $DOS) use ($OS) {
        return $c || (strpos($DOS, $OS) !== false);
    }, false);
}, false)) {
    echo "True";
}

Output:

True

This can also be written more simply as a nested foreach loop:

$found = false;
foreach ($outsideService as $OS) {
    foreach ($DepartingOS as $DOS) {
        if (strpos($DOS, $OS) !== false) {
            $found = true;
            break 2;
        }
    }
}
if ($found) {
    echo "True";
}

Demo on 3v4l.org

Upvotes: 1

Related Questions