Skip to content

Instantly share code, notes, and snippets.

@Lysak
Created February 19, 2026 16:13
Show Gist options
  • Select an option

  • Save Lysak/d14a063a5cd1a06b282e3236f01ea657 to your computer and use it in GitHub Desktop.

Select an option

Save Lysak/d14a063a5cd1a06b282e3236f01ea657 to your computer and use it in GitHub Desktop.
php test task
<?php
//
// //count(array_filter($this->getUsers(), fn($user) => $user['city_id'] === $cityId));
class Test
{
/**
* Example:
* [
* 1 => 'Robert De Niro',
* 2 => 'Leonardo DiCaprio',
* 3 => 'Tom Hanks',
* 4 => 'Angelina Jolie',
* ]
*
* @return array[]
*/
public function getUserNamesMap(): array
{
$data = [];
foreach ($this->getUsers() as $user) {
$data[$user['id']] = $user['name'];
}
return $data;
}
/**
* Example:
* [
* ['id' => 1, 'name' => 'Robert De Niro', 'city' => 'Lutsk'],
* ['id' => 2, 'name' => 'Leonardo DiCaprio', 'city' => 'Donetsk'],
* ['id' => 3, 'name' => 'Tom Hanks', 'city' => 'Lutsk'],
* ['id' => 4, 'name' => 'Angelina Jolie', 'city' => ''],
* ]
*
* @return array[]
*/
public function getUsersInfo(): array
{
$getUsers = $this->getUsers();
$getCities = $this->getCities();
$getCitiesMap = [];
foreach ($getCities as $city) {
$getCitiesMap[$city['id']] = $city['name'];
}
foreach ($getUsers as $index => $user) {
$getUsers[$index]['city'] = $getCitiesMap[$user['city_id']] ?? '';
unset($getUsers[$index]['city_id']);
}
return $getUsers;
}
/**
* Example:
* [
* 'Lutsk' => 2,
* 'Donetsk' => 1,
* 'Kyiv' => 0,
* ]
*
* @return array[]
*/
public function getPopulation(): array
{
$getCities = $this->getCities();
$getUsers = $this->getUsers();
$data = [];
$population = [];
foreach ($getUsers as $user) {
$cityId = $user['city_id'];
if (!isset($data[$cityId])) {
$data[$cityId] = 1;
} else {
$data[$cityId]++;
}
}
foreach ($getCities as $city) {
$population[$city['name']] = $data[$city['id']] ?? 0;
}
return $population;
}
private function getUsers(): array
{
return [
['id' => 1, 'name' => 'Robert De Niro', 'city_id' => 1],
['id' => 2, 'name' => 'Leonardo DiCaprio', 'city_id' => 2],
['id' => 3, 'name' => 'Tom Hanks', 'city_id' => 1],
['id' => 4, 'name' => 'Angelina Jolie', 'city_id' => 3],
];
}
private function getCities(): array
{
return [
['id' => 1, 'name' => 'Lutsk'],
['id' => 2, 'name' => 'Donetsk'],
['id' => 4, 'name' => 'Kyiv'],
];
}
}
$test = new Test();
echo 'UserNamesMap:' . PHP_EOL;
var_dump($test->getUserNamesMap());
echo 'UsersInfo:' . PHP_EOL;
var_dump($test->getUsersInfo());
echo 'Population:' . PHP_EOL;
var_dump($test->getPopulation());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment