Current Location: Home> Latest Articles> Use array_combine instead of looping to construct arrays

Use array_combine instead of looping to construct arrays

gitbox 2025-05-29

1. Basic usage of array_combine

array_combine receives two arrays as parameters, the first array as key, and the second array as value. If the two arrays have different lengths, Warning is thrown and false is returned.

 $keys = ['name', 'email', 'age'];
$values = ['Alice', '[email protected]', 30];
$result = array_combine($keys, $values);

// Output:['name' => 'Alice', 'email' => '[email protected]', 'age' => 30]
print_r($result);

Compared with the traditional foreach writing method, this method is more compact and the code is more readable.


2. Common writing methods of foreach construction

Using foreach to build associative arrays is also a common way, the code is as follows:

 $keys = ['name', 'email', 'age'];
$values = ['Alice', '[email protected]', 30];
$result = [];

foreach ($keys as $index => $key) {
    $result[$key] = $values[$index];
}

The advantage of this approach is its flexibility, and it can add logical processing during the build process, such as formatting data or skipping certain values.


3. Performance comparison: array_combine vs foreach

If from a performance perspective, array_combine is an internal function implemented in C language, and there is almost no gap when dealing with small amounts of data. But when dealing with large arrays (such as thousands of key-value pairs), it usually performs slightly better than manual foreach .

However, performance improvements are not an order of magnitude difference, and are usually obvious in millions of iterations. Here is a simple example of a benchmark (for reference only):

 $keys = range(1, 100000);
$values = range(100001, 200000);

// use array_combine
$start = microtime(true);
array_combine($keys, $values);
echo 'array_combine: ' . (microtime(true) - $start) . "s\n";

// use foreach
$start = microtime(true);
$result = [];
foreach ($keys as $i => $key) {
    $result[$key] = $values[$i];
}
echo 'foreach: ' . (microtime(true) - $start) . "s\n";

In most cases, array_combine will be slightly better, but the difference between the two will not exceed 5-10%.


4. Use scenario analysis and skills

1. When the data source is highly reliable, array_combine is preferred.

If you are sure that the two arrays have the same length and the data structure is stable, using array_combine is a smarter choice, not only is the code shorter, but the probability of error is low.

 $userFields = ['id', 'name', 'email'];
$userData = [101, 'John Doe', '[email protected]'];

$user = array_combine($userFields, $userData);

2. Foreach is required to enhance error tolerance when the length is inconsistent

If there is a possibility of data inconsistency, such as an array returned by the database and another input by the user, it is recommended to use foreach and add verification logic:

 $result = [];
$minLength = min(count($keys), count($values));
for ($i = 0; $i < $minLength; $i++) {
    $result[$keys[$i]] = $values[$i];
}

Or logging for subsequent troubleshooting:

 if (count($keys) !== count($values)) {
    error_log("Inconsistent array length: keys(" . count($keys) . "), values(" . count($values) . ")");
}

3. A better alternative when combining array_map

In some cases, you may use array_map and array_combine at the same time to improve chain processing power:

 $raw = ['John', '[email protected]', 28];
$keys = ['name', 'email', 'age'];

$user = array_combine($keys, array_map('trim', $raw));

This method is both concise and nests data preprocessing logic.