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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
keys The keys (strings or integers).
values The values, matched by position.

Return value

The combined array.

Examples

Keys plus valuesTry it yourself
<?php
print_r(array_combine(["name", "age"], ["Ada", 36]));

Output

Array
(
    [name] => Ada
    [age] => 36
)
Turn a CSV row into a recordTry it yourself
<?php
$header = ["id", "title"];
$row = ["7", "Arrays in PHP"];
$record = array_combine($header, $row);
echo $record["title"], "\n";

Output

Arrays in PHP
Lengths must matchTry it yourself
<?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

VersionChange
PHP 5.0Added
PHP 8.0Throws a ValueError when the counts differ, instead of returning false.

In other languages

Was this page helpful?