Page 1 of 1

how to check if two arrays matches with each other

Posted: Tue Dec 29, 2009 8:57 pm
by lauthiamkok
Hi,
How to check if two arrays matches with each other?

Code: Select all

$array = array("arts","photograph","drawing");
$patern = array("photograph","drawing");
 
if (in_array($patern, $array))  {
   echo 'found';
}
This is not working obviously.

But this works if $pattern is just a value or string, like this,

Code: Select all

$array = array("arts","photograph","drawing");
$patern = "photograph";
 
if (in_array($patern, $array))  {
   echo 'found';
}
But I have a couple of keywords in $pattern I want to check if any of them matches the keywords in $array...

Many thanks if you have any idea.

Thanks,
Lau

Re: how to check if two arrays matches with each other

Posted: Tue Dec 29, 2009 9:10 pm
by omniuni

Code: Select all

$array = array("arts","photograph","drawing");
$pattern = array("photograph","drawing");
$hits = null;
 
foreach($pattern as $checkmatch){
if (in_array($checkmatch, $array))  {
   $hits++;
}
}
 
echo 'Found '.$hits.' matches.';

Re: how to check if two arrays matches with each other

Posted: Tue Dec 29, 2009 9:14 pm
by Eran
You can either check for a boolean match:

Code: Select all

$array = array("arts","photograph","drawing");
$pattern = array("photograph","drawing");
$isSame = $pattern == $array;
var_dump($isSame);
Or get the difference:

Code: Select all

$diff = array_diff($array,$pattern); //$diff is empty if they are identical, else contains the differing parts

Re: how to check if two arrays matches with each other

Posted: Tue Dec 29, 2009 9:23 pm
by lauthiamkok
omniuni wrote:

Code: Select all

$array = array("arts","photograph","drawing");
$pattern = array("photograph","drawing");
$hits = null;
 
foreach($pattern as $checkmatch){
if (in_array($checkmatch, $array))  {
   $hits++;
}
}
 
echo 'Found '.$hits.' matches.';
got it! thank you very much! :D