3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Person { public $id; public $name; public $phones = []; public function __construct($id, $name) { $this->id = $id; $this->name = $name; } public function addPhone($phone) { $this->phones[] = $phone; } } /** * @return Person[] */ function statementToPersonList(iterable $stmt): array { $personList = []; foreach ($stmt as $row) { $id = $row['id']; $name = $row['name']; $number = $row['number']; if (!isset($personList[$name])) { $personList[$name] = new Person($id, $name); } $personList[$name]->addPhone($number); } return $personList; } $personList = statementToPersonList([ ['id' => 1, 'name' => 'Alice', 'number' => 'n1'], ['id' => 2, 'name' => 'Alice', 'number' => 'n2'], ['id' => 3, 'name' => 'Bob', 'number' => 'n3'], ['id' => 4, 'name' => 'Carol', 'number' => 'n4'], ['id' => 5, 'name' => 'Alice', 'number' => 'n5'], ]); print_r($personList);

preferences:
127.46 ms | 404 KiB | 5 Q