PHP Reference ยท Array Functions
PHP array_combine() function
Reference for PHP array_combine(): build an associative array from one array of keys and one of values, with duplicate keys, size mismatch and ValueError.
The array_combine() function creates a new array by using the values of one array as keys and the values of another as the values. Both arrays must have the same number of elements; the first key is paired with the first value, and so on.
It is handy for turning a header row and a data row into a record, or for pairing parallel lists.
$record = array_combine(["id", "name"], [7, "Ada"]); print_r($record); // ["id" => 7, "name" => "Ada"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_combine(array $keys, array $values): array
| Name | Description |
|---|---|
$keys |
Array whose values become the keys. |
$values |
Array whose values become the values. |
Return value: the combined array.
Errors / Exceptions: throws ValueError (PHP 8.0+) if the arrays have different numbers of elements. In PHP 7 it returned false with a warning.
Usage notes
- Keys are converted to strings first, then follow the normal array key rules:
"5"becomes integer 5,truebecomes the string"1"(so key 1),nullbecomes"", and a float such as1.5becomes the string key"1.5". - Duplicates collapse. If two keys are equal, the later value overwrites the earlier one and the result is shorter than the inputs.
- Only the values of each input are used; the original keys of both arrays are ignored, and pairing is by position.
- Inverse:
array_keys()andarray_values()split an array back into two lists. - Alternatives:
array_fill_keys($keys, $value)gives every key the same value, andarray_flip()swaps keys and values of one array. - Arrays or objects as keys cause a
TypeError("Illegal offset type").