friends.php
The module that shows a userâs friends and followers is Example 21-10, friends.php. This interrogates the friends
table just like the members.php program, but only for a single
user. It then shows all of that userâs mutual friends and followers, along
with the people he is following.
All the followers are saved into an array called $followers
and all the people being followed are
placed in an array called $following
.
Then a neat piece of code is used to extract all those that are both
following and followed by the user, like this:
$mutual = array_intersect($followers, $following);
The array_intersect
function
extracts all members common to both arrays and returns a new array
containing only those people. This array is then stored in $mutual
. Now itâs possible to use the array_diff
function for each of the $followers
and $following
arrays to keep only those people who
are not mutual friends, like this:
$followers = array_diff($followers, $mutual); $following = array_diff($following, $mutual);
This results in the array $mutual
containing only mutual friends, $followers
containing only followers (and no
mutual friends), and $following
containing only people being followed (and no mutual friends).
Armed with these arrays, itâs a simple matter to separately display
each category of members, as can be seen in Figure 21-6. The PHP sizeof
function returns the number of elements in an array; here I use it just to trigger code when the size is nonzero (that is, when friends ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.