Core\Arr::fillKeys
Core\Arr::fillKeys(array<int|uint|string> $keys, T $value): array<T>Core\Arr::fillKeys( array<int|uint|string> $keys, T $value, ): array<T>
Returns an array that holds one value under every key you name.
You give a list of keys and a single value. Each key becomes an entry, and every entry holds that value. The keys come from the values of the list you pass. The keys that list uses for itself are ignored. A key is a whole number or a text, and 1 and "1" are one key. Naming the same key twice gives one entry. An empty list of keys returns an empty array.
When you want the keys 0, 1, 2 and so on instead of your own, use Core\Arr::fill.
The examples below show an empty form, a set of allowed file formats, and a tally that starts at zero for every state an order can have.
Parameters
$keysarray<int|uint|string>The keys to store under, given as the array's values. Each is anint, auintor astring. The array's own keys are ignored.$valueTThe value of every entry.
Return value
Returns array<T>. One entry per distinct key, in the order each key first appears. 1 and "1" are one key.
Changelog
| Version | Change |
|---|---|
0.0.6 | A Core\Arr function that takes a key, such as hasKey, gave a compile error for a uint key (an unsigned whole number). It now takes a uint key, as $a[$key] already did. So Core\Arr::fillKeys($ids, true) works when $ids is a list of uint values. |
Examples
An empty form
<?nvs// Shows how to build an array that holds the same value under several keys.
array<string> $fields = ['name', 'email', 'city'];
// One entry per field name, each holding an empty text.array<string> $form = Core\Arr::fillKeys($fields, '');
// This prints one line per field, each ending in a colon and a space.foreach ($form as string $field => string $value) { echo $field, ': ', $value, "\n";}name:email:city:A set you can look up in
<?nvs// Shows how to build a set. Looking up a key stays fast as the set grows, so// this is what you want when you test many values against one list.
array<string> $formats = ['png', 'jpeg', 'webp'];array<bool> $allowed = Core\Arr::fillKeys($formats, true);
// This prints "png is allowed".if (Core\Arr::hasKey($allowed, 'png')) { echo "png is allowed\n";}
// This prints "gif is not allowed".if (!Core\Arr::hasKey($allowed, 'gif')) { echo "gif is not allowed\n";}png is allowedgif is not allowedA tally that starts at zero
<?nvs// Shows how to count orders by their state. Every state starts at 0, so a// state that no order has still appears in the result.
array<string> $states = ['new', 'paid', 'shipped'];array<int> $counts = Core\Arr::fillKeys($states, 0);
array<string> $orders = ['paid', 'new', 'paid'];foreach ($orders as string $state) { $counts[$state] = $counts[$state] + 1;}
// This prints "new: 1", "paid: 2" and "shipped: 0".foreach ($counts as string $state => int $count) { echo $state, ': ', $count, "\n";}new: 1paid: 2shipped: 0