0

Possible Duplicate:
Find common values in multiple arrays with PHP

I'm trying to find the number of friends two users have in common. Each users friends user id's are stored in the data base like this: 12, 13, 14. This is my code.

$my_friends = explode(',', $my_friends);
print_r($my_friends);

This outputs: Array ( [0] => 12 [1] => 13 [2] => 14 )

These are my friends user id's. Now for the next user:

$users_friends = explode(',', $users_friends);
print_r($users_friends);

This outputs: Array ( [0] => 12 )

How do I show that user 1 and user 2 have id 12 in common ?

Community
  • 1
  • 1
Elmer Almeida
  • 229
  • 1
  • 3
  • 7

3 Answers3

4

Besides suggesting that you should normalise your database, which would make this easy to do with a simple SQL Query:

Explode the $myFrieds and $users_friends arrays, then use the array_intersect() function to find the common entries, and count() those

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1

You could use array_intersect().

print_r(array_intersect($my_friends, $users_friends));

will output Array ( [0] => 12 )

Havelock
  • 6,913
  • 4
  • 34
  • 42
1

You can use array_intersect:

$common_friends = array_intersect($my_friends, $users_friends);
Nelson
  • 49,283
  • 8
  • 68
  • 81