rnfriends.php

The module that shows a user’s friends and followers is Example 20-11, rnfriends.php. This interrogates the rnfriends table just like the rnmembers.php program, but only for a single user. It then shows all of that user’s mutual friends and followers along with the people they are 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 20-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, friends of ...

Get Learning PHP, MySQL, and JavaScript 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.