Core\ObjectMap::values
$objectMap->values(): array<V>Returns every value of a Core\ObjectMap as a list. The values are in the order their keys were added. The value at each position belongs to the key at the same position in the list that keys returns.
The list is a new array. If you change the map after the call, the list does not change. If the map is empty, the result is an empty array. A null value is in the list like any other value.
Use values when you need the values and not the objects they belong to, for example to add them up or to pass them to a function that takes an array.
The examples show listing the values, matching each value to its key, and a common use: adding up the total of all open shopping carts.
Return value
Returns array<V>. A new array<V> list. It is empty for an empty map. Each position matches the same position in keys().
Examples
List the values
<?nvs// Shows how to get all the values of a map as a list.
final class Sensor{ public string $room;
public function constructor(string $room) { $this->room = $room; }}
Core\ObjectMap<Sensor, float> $temperature = new Core\ObjectMap<Sensor, float>();$temperature->set(new Sensor('hall'), 19.5);$temperature->set(new Sensor('office'), 22.0);$temperature->set(new Sensor('attic'), 15.25);
// `values` returns the three readings in the order their sensors were added.array<float> $readings = $temperature->values();
// This prints 19.5, 22 and 15.25.foreach ($readings as float $reading) { echo $reading, "\n";}19.52215.25Match values to keys
<?nvs// Shows that `keys` and `values` list their entries in the same order.
final class Team{ public string $name;
public function constructor(string $name) { $this->name = $name; }}
Core\ObjectMap<Team, ?int> $scores = new Core\ObjectMap<Team, ?int>();$scores->set(new Team('red'), 3);// The blue team has no score yet, so its value is `null`.$scores->set(new Team('blue'), null);$scores->set(new Team('green'), 5);
array<Team> $teams = $scores->keys();array<?int> $points = $scores->values();
// The value at each position belongs to the team at the same position.// This prints "red 3", "blue -" and "green 5".int $i = 0;while ($i < Core\Arr::count($teams)) { echo $teams[$i]->name, ' ', $points[$i] ?? '-', "\n"; $i = $i + 1;}red 3blue -green 5Add up open carts
<?nvs// Shows how to add up the values of a map, here the totals of all open shopping carts.
final class Cart{ public string $id;
public function constructor(string $id) { $this->id = $id; }}
// The map stores the total of each open cart, in cents.Core\ObjectMap<Cart, int> $totals = new Core\ObjectMap<Cart, int>();$totals->set(new Cart('c-1'), 1999);$totals->set(new Cart('c-2'), 450);$totals->set(new Cart('c-3'), 12000);
// `values` gives the totals as a list, and `Core\Arr::sum` adds them up.// This prints 14449.echo Core\Arr::sum($totals->values()), "\n";14449