0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this works though it's hard for me to understand (learn). What does the $c reference (abbrevieation)?
@Burndog I apologise. Sometimes I get carried away with PHPs array functions. Anyway to answer your question, $c is an accumulator and it just tracks the current state of whether we have found a match or not; it is the value ultimately returned by array_reduce. But I have edited my answer with a simple nested foreach loop which is probably better code to use anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.