PHP 8 reference · Array Functions
PHP array_combine() Function
Create an array by using one array for keys and another for values. Both arrays must have the same number of elements.
PHP 8 Since 5.0
Syntax
array_combine(array $keys, array $values): array
Parameters
| Parameter | Description |
|---|---|
keys |
The keys (strings or integers). |
values |
The values, matched by position. |
Return value
The combined array.
Examples
<?php
print_r(array_combine(["name", "age"], ["Ada", 36]));
Output
Array
(
[name] => Ada
[age] => 36
)<?php
$header = ["id", "title"];
$row = ["7", "Arrays in PHP"];
$record = array_combine($header, $row);
echo $record["title"], "\n";
Output
Arrays in PHP
<?php
try {
array_combine(["a", "b"], [1]);
} catch (ValueError $e) {
echo $e->getMessage(), "\n";
}
Output
array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements
Version history
In other languages
zip()· Pythondict()· PythonObject.fromEntries()· JavaScript
Related
array_fill_keys()· Create an array from a list of keys, giving every key the same value. Useful for defaults and counters.array_flip()· Swap keys and values, so each value becomes a key. Values must be strings or integers; duplicates keep the last key.array_keys()· Return all the keys of an array, or only the keys whose value matches a search value.array_values()· Return all the values of an array as a list re-indexed from 0. Often used after array_filter() or unset().- PHP Arrays · tutorial
- PHP Array Functions · tutorial