I’m developing a custom database search (MySQL). The results come down to a group of several arrays (in this case sub-arrays of $freelistings, see below), and I need to find out what values are common to ALL of these arrays. I’ve got ‘array_intersect’ to do that, as shown below (though I’m not entirely sure whether it will take unlimited parameters):
$finalresult = array_intersect($freelistings['dbl'], $freelistings['twn'], $freelistings['sgl'], $freelistings['fam']);
It works a treat when all the sub-arrays are present. The final result is an array containing ONLY those values that are common to all the sub-arrays.
My problem is that I can’t be sure that all of these sub-arrays will actually exist, and I can’t insert dummies as that would invalidate the results. I do know that at least one must exist, and it’s quite easy to deal with that situation:
if (count($freelistings) == 1) {
$finalresult = $freelistings;
} else {
Do something else
}
The ‘Do something else’ would be to assemble the parameters for ‘array_intersect’ using only those sub-arrays that actually exist. So far I’ve not come up with a solution. I’ve tried assembling those sub-arrays that do exist into a string that could be used as the argument for ‘array_intersect’, but I get a (fatal) whitespace error on the third line of the snippet shown, presumably because PHP doesn’t like a $ inside a quote.
$textlist = "";
if (isset($freelistings['dbl'])) {
$textlist .= "$freelistings['dbl'],";
}
if (isset($freelistings['twn'])) {
$textlist .= "$freelistings['twn'],";
}
if (isset($freelistings['sgl'])) {
$textlist .= "$freelistings['sgl'],";
}
if (isset($freelistings['fam'])) {
$textlist .= "$freelistings['fam'],";
}
$textlist = substr($textlist, 0, -1); // cuts off final comma
echo $textlist . '<br />';
$finalresult = array_intersect($textlist);
None of the sub-arrays are huge. In my tests they only have about four values each, but this could go up to around twenty or more in production. Of these values there may be several that are found in all sub-arrays. There may eventually be more than four possible sub-arrays, but it seems unlikely there would be more than four or five in any one instance.
Can anyone help, please ?