how to check if two arrays matches with each other

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

how to check if two arrays matches with each other

Post 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
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

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

Post 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.';
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

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

Post 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
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

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

Post 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
Post Reply