Core\Arr::fromKeysAndValues
Returns an array that pairs a list of keys with a list of values, one for one.
You give two arrays that hold the same number of entries. The first key goes with the first value, the second key with the second value, and so on. Both arrays contribute their values, so the keys they use for themselves are ignored. A key is a whole number or a text, and 1 and "1" are one key. When the same key is given twice, the entry keeps the position of the first one and holds the last value given for it. Two arrays of different lengths throw a RuntimeError.
The examples below show two lists paired into one array, a line of a CSV file read under its column names, and a lookup that finds a name by its id.
Parameters
$keysarray<int|uint|string>The keys, given as the array's values. Each is anint, auintor astring. The array's own keys are ignored.$valuesarray<T>The values, in the same order. The array's own keys are ignored.
Return value
Returns array<T>. One entry per pair, in the order of $keys. A repeated key keeps its first position and takes its last value. 1 and "1" are the same key.
Errors
RuntimeErrorThe two arrays have different numbers of entries.
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
Pair two lists
<?nvs// Shows how to pair two lists into one array. The first list gives the keys// and the second gives the values.
array<string> $fields = ['city', 'country'];array<string> $answers = ['Berlin', 'Germany'];
array<string> $address = Core\Arr::fromKeysAndValues($fields, $answers);
// This prints "city: Berlin" and then "country: Germany".foreach ($address as string $field => string $value) { echo $field, ': ', $value, "\n";}city: Berlincountry: GermanyA row under its column names
<?nvs// Shows how to read one line of a CSV file under the names in its first line.// You can then use a column name instead of counting positions.
array<string> $columns = ['id', 'name', 'city'];array<string> $line = ['7', 'Ada', 'London'];
array<string> $record = Core\Arr::fromKeysAndValues($columns, $line);
// This prints "Ada lives in London".echo $record['name'], ' lives in ', $record['city'], "\n";Ada lives in LondonA lookup from an id to a name
<?nvs// Shows how to turn the rows of a database query into a lookup. Finding a name// by its id then needs no loop over the rows.
array<array<string>> $rows = [ ['id' => '7', 'name' => 'Ada'], ['id' => '9', 'name' => 'Grace'],];
array<string> $names = Core\Arr::fromKeysAndValues( Core\Arr::column($rows, 'id'), Core\Arr::column($rows, 'name'),);
// This prints "Grace".echo $names['9'], "\n";Grace