Avatar of johnkolbert
johnkolbert
 asked on

Comparing Two Arrays with PHP

Is there a way to do the following:

Compare the elements of two arrays and see if any element in one matches any element in the other (the arrays may be different lengths).

For instance:

Array 1 contains:
red
green
blue
balck
white

Array 2 contains:
pink
purple
blue

The resulting expression would show "true" since arrays 1 and 2 both have blue.

Is this possible?
PHP

Avatar of undefined
Last Comment
wildzero

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
wildzero

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
wildzero

You can even modify that do to

$a1 = array('red','green','blue','black','white');
$a2 = array('pink','purple','blue');

$a3 = array_intersect($a1,$a2);
If (count($a3) > 0) {
  echo "Has Some Items";
  print_r($ar); //this will show the matching items.
} else {
  echo "No matching items";
}
johnkolbert

ASKER
Ah, perfect. That seems to be what I'm looking for! Many thanks!
wildzero

print_r($ar); //this will show the matching items.

should be

print_r($a3); //this will show the matching items.

:-)
Glade it helped.



I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck