...

/

Solution: Filtering Users in Social Network Data with PHP 8

Solution: Filtering Users in Social Network Data with PHP 8

A detailed review of the solution to the previous challenge involving extracting data from classes with newly introduced methods and OOP concepts in PHP 8.

We'll cover the following...

The code widget below contains the solution to the challenge. We will also go through a step-by-step explanation of the solution.

Solution

Press + to interact
<?php
class User {
public function __construct(
private string $name,
private string $email,
private ?int $age = null,
private array $friends = []
) {}
public function getName(): string {
return $this->name;
}
public function getEmail(): string {
return $this->email;
}
public function getAge(): ?int {
return $this->age;
}
public function getFriends(): array {
return $this->friends;
}
public function getGender(): string {
// Assume gender is determined by the last letter of the name
return substr($this->name, -1) === 'a' ? 'Female' : 'Male';
}
}
// Example usage
$users = [
new User('Alice', 'Alice@example.com', 23, ['Bob', 'Charlie']),
new User('Bob', 'Bob@example.com', 30, ['Alice', 'Dave']),
new User('Charlie', 'Charlie@example.com', 40, ['Alice']),
new User('Dave', 'Dave@example.com', 25, ['Bob']),
];
// Get the first friend of the first user using nullsafe and nested ternary operators
$firstFriend = $users[0]?->getFriends()[0] ?? null;
echo $firstFriend;
echo "\n------------------------------------------------------\n";
// Get all users whose email starts with a friend's name using arrow function and str_starts_with()
$friendName = 'Bob';
$usersWithFriendNameInEmail = array_filter($users, fn($user) => str_starts_with($user->getEmail(), $friendName));
print_r($usersWithFriendNameInEmail);
echo "\n------------------------------------------------------\n";
// Get all users who have a friend named "Bob" using arrow function and str_contains()
$friendName = 'Bob';
$usersWithBobFriend = array_filter($users, fn($user) => str_contains(implode('', $user->getFriends()), $friendName));
print_r($usersWithBobFriend);
echo "\n------------------------------------------------------\n";
// Create a comma-separated list of friends for each user using arrow function, str_contains() and str_replace()
$friendList = array_map(fn($user) => $user->getName() . ': ' . str_replace(',', ', ', implode(',', $user->getFriends())), $users);
print_r($friendList);
echo "\n------------------------------------------------------\n";

Let’s get into the code:

  • Lines 3–8: Define a constructor using a constructor property promotion. Here, $name is a private string property, $email is a private string property, $age is a private integer property, and $friends is also a private array ...