Home > front end >  Check if array is present in another array without exact match
Check if array is present in another array without exact match

Time:04-14

$source = ['domain.com', 'subdomain.value.com'];
$str = ['value.com', 'blur.de', 'hey.as'];

How to check if any of $str is present in $source?

I've tried in_array or array_intersect but both seem to check for exact values, so none match.

In this example, it should match as 'value.com' is present in 'subdomain.value.com'.

CodePudding user response:

You could replace elements in $source with elements in $str and see how many replacements were made:

str_replace($str, '', $source, $count);
echo $count;

CodePudding user response:

<?php
$source = ['domain.com', 'subdomain.value.com', 'hey.as'];
$str = ['value.com', 'blur.de', 'hey.as'];

function any_item_in_array($needles, $haystack) {
    foreach($needles as $needle) {
        if (in_array($needle, $haystack)) return true;
    }
    return false;
}

$found = any_item_in_array($str, $source);
  • Related