Jump to content


Photo

count matching results in two arrays


  • Please log in to reply
1 reply to this topic

#1 micah1701

micah1701
  • Members
  • PipPipPip
  • Advanced Member
  • 613 posts
  • LocationEllington, CT USA

Posted 15 June 2006 - 04:22 PM

So I have two arrays.
the first lists the winners of a series of games:

$winners = Array
(
[0] => New England
[1] => Buffalo
[2] => pittsburgh
[3] => St. Louis
)

and the other is a person's guess of who will win

$picks = Array
(
[0] => New England
[1] => NY Giants
[2] => Dallas
[3] => St. Louis
)

What is the best way to compare the arrays to see how many guesses in $picks match the results in $winners

if I had 1 pick, I could use in_array but I need to check each value in picks against the $winners array and determine a value for total matches. (ie, "2" in the example above)

thoughts on the best way to do it?
I always come up w/ hack jobs and make it 20 times more complicated then it needs to be.

[EDIT]

ok, well here's what I have:

  foreach($picks as $pick){
  if(in_array($pick,$winners)){
   $total = $total + 1;
   }
  }
  echo "you got $total correct";

I guess thats pretty simple if no one has a better idea.

"Confidence in the face of risk."

#2 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 15 June 2006 - 08:43 PM

Shorter solution:
<?php
$matches = array_intersect($winners,$picks);
echo "You got ".count($matches)." right";
?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users