How can PHP be optimized to efficiently handle friend list comparisons between tables?

To efficiently handle friend list comparisons between tables in PHP, you can use SQL queries to fetch the friend lists from the tables and then perform the comparison in PHP using array functions like array_intersect. This approach minimizes the data transferred between the database and PHP, improving performance.

// Assuming $user1Friends and $user2Friends are arrays containing the friend IDs of each user fetched from the database

// Fetch friend list of user 1
$user1Friends = [];
$query = "SELECT friend_id FROM friends_table WHERE user_id = $user1_id";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
    $user1Friends[] = $row['friend_id'];
}

// Fetch friend list of user 2
$user2Friends = [];
$query = "SELECT friend_id FROM friends_table WHERE user_id = $user2_id";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
    $user2Friends[] = $row['friend_id'];
}

// Compare friend lists using array_intersect
$mutualFriends = array_intersect($user1Friends, $user2Friends);