find out sub array is present in main array or not or how to use FIND_IN_SET

Hi,

my first array
[php]

Array
(
    [0] => 1
    [1] => 9
)
[/php]
and second array is
[php]
Array
(
    [0] => 1,2,3,4,5,6,7,8,9

    [1] => 1,2,3,4,8,9
    [2] => 3,4,5,6,7,8,9
)
[/php]
how do i fetch only those entries from second array  which are having 1 and 9 in Comma separated values

Check out http://php.net/manual/en/function.explode.php and the see also this should give you what you’re looking for.

Something like this might help you out.
It takes the “needle” (first array) and joins it together in a regular expression, then is loops through the “haystack” (second array) and tries to match the expression. As it find correct values it builds a new array and returns the result.

[php]
function findInArray(array $needle, array $haystack) {
$results = array();
$pattern = ‘/^(?=.’ . implode(’)(?=.’, $needle) . ‘)/’;
foreach ($haystack as $value) {
if (preg_match($pattern, $value)) {
$results[] = $value;
}
}

    return $results;
}

[/php]

Potentially a nice use case for array filter…

[php]$find = array(1,2);

$arrayTwo = array(
‘1,2,3,4,5,6,7,8,9’,
‘1,2,3,4,8,9’,
‘3,4,5,6,7,8,9’
);

print_r(array_filter($arrayTwo, function($csv) use ($find) {
$array = explode(’,’, $csv);
$matches = array_intersect($array, $find);
return count($matches) > 0;
}));

// or if you’re a one line kinda guy
print_r(array_filter($arrayTwo, function($csv) use ($find) {
return count(array_intersect(explode(’,’, $csv), $find)) > 0;
}));[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service