O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 of that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required