Skip to content

Core\Arr::values

Core\Arr::values(array<T> $a): array<T>Core\Arr::values(
    array<T> $a,
): array<T>

Gives you every value of an array, as a list.

The values come back in the order they were put in, and the keys are dropped. The list is numbered from 0, so the first value is at position 0 and the second at position 1.

The list is a fresh array. You can walk it, count it or change it, and the array you asked about keeps its own keys and entries.

A common use is after Core\Arr::filter, which keeps the key of every entry it keeps. The entries that are left can have gaps in their numbering, and this gives you the same entries numbered from 0 again.

An array with no entries gives you an array with no entries.

Parameters

  • $aarray<T>The array whose values are wanted.

Return value

Returns array<T>. A list renumbered from "0".

Examples

The values in an array

<?nvs
// Shows how to read the values of an array as a plain list.
array<string> $user = ['name' => 'Ada', 'city' => 'Wien', 'job' => 'engineer'];
// The values come back in the order they were put in, and the keys are gone.
// This prints `Ada, Wien, engineer`.
echo Core\Str::join(Core\Arr::values($user), ', '), "\n";
// The list is numbered from 0, so the first value is at position 0. This
// prints `Ada`.
echo Core\Arr::values($user)[0], "\n";
Output
Ada, Wien, engineer
Ada

The list is a new array

<?nvs
// Shows that `Core\Arr::values` builds a new array. The array you pass in keeps
// its own keys and entries.
array<int> $stock = ['apples' => 12, 'pears' => 4];
array<int> $counts = Core\Arr::values($stock);
$counts[] = 99;
// The new list has three entries and $stock still has two, so this prints
// `3 2`.
echo Core\Arr::count($counts), ' ', Core\Arr::count($stock), "\n";
// $stock is still read by its own keys. This prints `12`.
echo $stock['apples'], "\n";
// An array with no entries gives you an array with no entries, so this
// prints `0`.
array<int> $empty = [];
echo Core\Arr::count(Core\Arr::values($empty)), "\n";
Output
3 2
12
0

Numbering a list again

<?nvs
// Numbers a list again after entries have been removed from it. This is what
// programs use `Core\Arr::values` for most often.
array<string> $colours = ['red', 'green', 'blue', 'grey'];
// `Core\Arr::filter` keeps the key of every entry it keeps, so the entries
// that are left are at the positions 0, 2 and 3.
array<string> $kept = Core\Arr::filter($colours, fn(string $colour) => $colour != 'green');
echo Core\Str::join(Core\Arr::keys($kept), ','), "\n";
// `Core\Arr::values` gives you the same entries at the positions 0, 1 and 2.
array<string> $list = Core\Arr::values($kept);
echo Core\Str::join(Core\Arr::keys($list), ','), "\n";
echo Core\Str::join($list, ','), "\n";
Output
0,2,3
0,1,2
red,blue,grey