Arrays7 min readExamples run on PHP 8.5.10

array_combine()

Learn how PHP 8.4 array_combine() pairs one array of keys with an array of values, what it returns, when it throws ValueError, and which pitfalls to avoid.

Signature

array_combine(array $keys, array $values): array

Purpose

array_combine() builds a new associative array from two separate lists. The first list supplies the keys, the second supplies the values, and elements are paired by position: the first key with the first value, the second key with the second value, and so on.

This is handy when data arrives as parallel lists, for example a header row of column names and a row of cell values, or two lists produced by different parts of a program. Instead of writing a loop with an index, you can pair them with one call.

Signature

Parameters and defaults

  • $keys: the array whose values become the keys of the result. The keys of this input array are ignored; only its values and their order matter. Values that are not valid array keys are converted to strings.
  • $values: the array whose values become the values of the result. Again, only the order of its values matters, not its own keys.

Neither parameter is optional, and there are no default values.

Return value and failure cases

The function returns the combined array. Since PHP 8.0.0, if the two arrays do not contain the same number of elements, a ValueError is thrown. Before PHP 8.0.0 the mismatch produced a warning and a false result, so older code that checks for false no longer matches how PHP 8 behaves. In PHP 8.4 you should catch the exception, or better, verify the counts yourself before calling.

Two empty arrays are a valid input and produce an empty array.

Example 1: pairing two lists

The simplest case matches the typical use: names in one array and their values in another.

Example
<?php
$keys = ['green', 'red', 'yellow'];
$values = ['avocado', 'apple', 'banana'];
echo json_encode(array_combine($keys, $values), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
{"green":"avocado","red":"apple","yellow":"banana"}

Each key is paired with the value at the same position, so green maps to avocado, red to apple and yellow to banana.

Example 2: duplicate keys

Array keys are unique, so if the same key appears more than once in $keys, later pairs overwrite earlier ones. The entry keeps the position where the key first appeared.

Example
<?php
$keys = ['a', 'b', 'a'];
$values = [1, 2, 3];
echo json_encode(array_combine($keys, $values), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
{"a":3,"b":2}

The result has only two entries. The key a first holds 1, then is overwritten with 3, while b keeps 2. The result therefore has fewer elements than the inputs, which surprises people who assume the sizes always match.

Example 3: empty input and a size mismatch

Example
<?php
echo json_encode(array_combine([], [])), "\n";
try {
    array_combine(['a', 'b'], [1]);
} catch (ValueError $e) {
    echo get_class($e), "\n";
}
Output
[]
ValueError

Two empty arrays give an empty array, which JSON encodes as []. Two keys with only one value cannot be paired, so a ValueError is thrown and caught.

Edge cases

  • Input keys are ignored. If $keys is [5 => 'x', 9 => 'y'], the resulting keys are x and y, not 5 and 9. The order of the elements is what counts.
  • Numeric strings become integer keys. As in any PHP array, a string such as "10" used as a key is stored as the integer 10.
  • Non-scalar keys. Key values that are not legal array keys are converted to strings, as the manual notes. Do not rely on exotic conversions; build keys from plain strings or integers.
  • Values can be anything. Nested arrays, objects, null and booleans are all fine as values, and they are copied into the result unchanged.
  • Value arrays with their own keys. If $values is itself associative, its keys are discarded and only its element order is used.

Common mistakes

  1. Expecting false on mismatch. That was the behavior before PHP 8.0.0. In PHP 8.4 a mismatch throws ValueError, and code such as if (array_combine($a, $b) === false) will never run its branch.
  2. Ignoring duplicates. If the keys come from user data or a CSV header, duplicates silently collapse entries. Check with count(array_unique($keys)) === count($keys) when uniqueness matters.
  3. Swapping the arguments. The keys come first. Reversing them can still run without error if the values are strings, producing a valid but wrong array.
  4. Assuming the input keys are preserved. Filtered arrays with gaps in their keys work fine, because only order matters, but do not expect those gaps to appear in the output.
  5. Not validating lengths from external data. When rows come from outside your program, compare count($keys) with count($values) first and handle the mismatch deliberately instead of letting the exception escape.
  • array_merge() joins arrays together rather than pairing them.
  • array_values() returns the values of an array with fresh numeric keys, useful for normalizing input before combining.
  • array_map() can transform each side before combining, or build pairs with several arrays at once.
  • array_walk() applies a callback to each member of an array in place.
  • array_keys(), array_flip() and array_fill_keys() solve neighboring problems when you already have only one list.

Recap

array_combine($keys, $values) pairs two arrays by position, using the first array's values as keys. Both arrays must have the same number of elements, otherwise PHP 8 throws ValueError. Duplicate keys overwrite earlier entries, the original keys of both inputs are ignored, and two empty arrays give an empty array.

Tested examples

Pairing two lists
<?php
$keys = ['green', 'red', 'yellow'];
$values = ['avocado', 'apple', 'banana'];
echo json_encode(array_combine($keys, $values), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
{"green":"avocado","red":"apple","yellow":"banana"}
Duplicate keys overwrite earlier values
<?php
$keys = ['a', 'b', 'a'];
$values = [1, 2, 3];
echo json_encode(array_combine($keys, $values), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
Output
{"a":3,"b":2}
Empty input and a size mismatch
<?php
echo json_encode(array_combine([], [])), "\n";
try {
    array_combine(['a', 'b'], [1]);
} catch (ValueError $e) {
    echo get_class($e), "\n";
}
Output
[]
ValueError