PHP associative arrays store information using key-value pairs. Sometimes, however, your keys and values are stored in two separate arrays, and you need to combine them.
The array_combine() function makes this easy by using one array for keys and another for their corresponding values.
In this guide, you'll learn how array_combine() works, how it handles duplicate keys, and how to use it with structured data.
What Is array_combine() in PHP?
The array_combine() function creates an associative array using the elements of one array as keys and the elements of another as values.
Its syntax is:
array_combine(array $keys, array $values): array
It accepts two parameters:
$keys— An array containing the keys for the new array.$values— An array containing the corresponding values.
Both arrays must contain the same number of elements.
The function returns a new associative array without modifying the original arrays.
Example 1: Combining Two Simple Arrays
Let's create an associative array using product names and their prices.
<?php
$products = ["Keyboard", "Mouse", "Monitor"];
$prices = [49.99, 24.50, 199.00];
$result = array_combine($products, $prices);
print_r($result);
Output:
Array
(
[Keyboard] => 49.99
[Mouse] => 24.5
[Monitor] => 199
)
The first element of $products becomes the key for the first element of $prices, and so on.
You can now access individual prices directly:
echo $result["Mouse"];
Output:
24.5
This is useful when you need to convert two related lists into a single lookup array.
Example 2: Creating an Array with Field Names
Another common use is combining field names with corresponding record values.
<?php
$fields = ["id", "name", "email"];
$values = [
101,
"Alex",
"[email protected]"
];
$user = array_combine($fields, $values);
print_r($user);
Output:
Array
(
[id] => 101
[name] => Alex
[email] => [email protected]
)
Each field name becomes a key, and its matching value is assigned automatically.
This approach is particularly useful when converting tabular records into associative arrays.
What Happens When Array Lengths Don't Match?
The two input arrays must have the same number of elements.
In PHP 8 and later, array_combine() throws a ValueError when their lengths differ.
<?php
$keys = ["name", "email", "age"];
$values = ["Alex", "[email protected]"];
try {
$result = array_combine($keys, $values);
} catch (ValueError $error) {
echo "The arrays must have equal lengths.";
}
Output:
The arrays must have equal lengths.
You can avoid this problem by checking the lengths before combining:
if (count($keys) === count($values)) {
$result = array_combine($keys, $values);
}
For applications using PHP versions earlier than 8.0, a length mismatch produces a warning and returns false instead.
How Are Duplicate Keys Handled?
If the first array contains duplicate keys, PHP cannot preserve every corresponding value under the same key.
The later value replaces the earlier one.
<?php
$keys = ["name", "email", "name"];
$values = [
"Alex",
"[email protected]",
"Taylor"
];
$result = array_combine($keys, $values);
print_r($result);
Output:
Array
(
[name] => Taylor
[email] => [email protected]
)
The second name value overwrites the first.
Also remember that PHP array keys can be integers or strings. Numeric strings that PHP recognizes as valid integer keys may be converted to integers.
Important: If every record must be preserved, check that the keys are unique before combining the arrays.
Practical Example: Converting Product Records into Associative Arrays
Imagine you're processing data from a spreadsheet or CSV-style source.
The column names are stored in one array, while individual records contain the corresponding values.
Let's convert those records into associative arrays.
Create a file named products.php:
<?php
declare(strict_types=1);
// Column names.
$columns = ["code", "product", "stock"];
// Product records.
$records = [
["KB-101", "Keyboard", 12],
["MS-102", "Mouse", 0],
["MN-103", "Monitor", 5]
];
// Validate column names.
if (count($columns) !== count(array_unique($columns))) {
exit("Duplicate column names.");
}
// Process each record.
foreach ($records as $values) {
if (count($columns) !== count($values)) {
echo "<p>Invalid record format.</p>";
continue;
}
// Convert values into an associative array.
$product = array_combine($columns, $values);
$status = $product["stock"] > 0
? $product["stock"] . " available"
: "Out of stock";
$description = $product["code"]
. " - "
. $product["product"]
. ": "
. $status;
echo "<p>" . htmlspecialchars(
$description,
ENT_QUOTES,
"UTF-8"
) . "</p>";
}
Browser output:
KB-101 - Keyboard: 12 available
MS-102 - Mouse: Out of stock
MN-103 - Monitor: 5 available
Each record is transformed into an associative array containing code, product, and stock.
The application can then reference fields by name instead of relying on numeric positions.
This example uses predefined data. When processing actual CSV files or external input, validate field values and data types before using them.
What Happens with Empty Arrays?
In PHP 8+, combining two empty arrays returns an empty array:
<?php
$result = array_combine([], []);
var_dump($result);
Output:
array(0) {
}
This is valid because both arrays contain the same number of elements.
array_combine() vs array_merge()
Although both functions combine arrays, they perform different operations.
| Function | Purpose |
|---|---|
array_combine() |
Uses one array's elements as keys and another array's elements as values. |
array_merge() |
Combines the entries of multiple arrays into one array. |
Use array_combine() when you have separate lists of keys and values. Use array_merge() when you want to merge existing arrays.
Common Mistakes
- Different array lengths: Ensure both arrays contain the same number of elements.
- Duplicate keys: Later values overwrite earlier values.
- Expecting the original arrays to change: The function returns a new array.
- Confusing keys with positions: Elements are paired in iteration order, not by matching their original array keys.
- Using unsuitable key values: Prefer predictable string or integer keys to avoid unexpected conversions.
Key Takeaways
array_combine()creates an associative array from two arrays.- The first array provides the keys, and the second provides the values.
- Both arrays must have equal lengths.
- In PHP 8+, mismatched lengths throw a
ValueError. - Duplicate keys cause earlier values to be overwritten.
- The original arrays remain unchanged.
- The function is useful for converting structured records and creating lookup arrays.
The array_combine() function provides a straightforward way to create associative arrays from separate lists of keys and values. It's especially helpful when processing tabular data, converting records, and organizing information for easier access.
For additional details, see the official PHP array_combine() documentation.