<?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";