PHP array_combine() - Complete Guide with Examples

Mahesh Mahesh Waghmare
4 min read

The array_combine() function creates an array by using one array for keys and another for values. It’s essential for transforming data structures and creating associative arrays.

This guide covers everything about array_combine(), from basic usage to advanced patterns.

Introduction to array_combine()

array_combine() merges two arrays into an associative array, using the first array as keys and the second as values.

Key Characteristics:

  • Requires equal array lengths
  • Returns associative array
  • Keys from first array
  • Values from second array

Common Use Cases:

  • Create associative arrays
  • Transform data structures
  • Map keys to values
  • Combine separate key/value arrays

Syntax and Parameters

Function Signature

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

Parameters

$keys (required):

  • Array to use as keys
  • Must be same length as $values
  • Keys must be valid (string or integer)

$values (required):

  • Array to use as values
  • Must be same length as $keys

Return Value

Returns associative array with keys from first array and values from second array.

Errors:

  • Returns false if arrays have different lengths
  • Warning if arrays are empty
Advertisement

Basic Usage Examples

Simple Combination

$keys = ['name', 'email', 'age'];
$values = ['John', 'john@example.com', 30];

$result = array_combine($keys, $values);
/*
Result:
[
    'name' => 'John',
    'email' => 'john@example.com',
    'age' => 30
]
*/

Numeric Keys

$keys = [0, 1, 2];
$values = ['apple', 'banana', 'orange'];

$result = array_combine($keys, $values);
// Result: [0 => 'apple', 1 => 'banana', 2 => 'orange']

Mixed Types

$keys = ['id', 1, 'status'];
$values = [100, 'active', true];

$result = array_combine($keys, $values);
// Result: ['id' => 100, 1 => 'active', 'status' => true]

Edge Cases and Errors

Different Array Lengths

$keys = ['a', 'b'];
$values = [1, 2, 3];

$result = array_combine($keys, $values);
// Warning: Array to string conversion
// Returns false or unexpected result

Solution: Ensure arrays have same length:

if (count($keys) === count($values)) {
    $result = array_combine($keys, $values);
} else {
    // Handle error
}

Empty Arrays

$result = array_combine([], []);
// Warning: array_combine(): Both parameters should have at least 1 element
// Returns false

Duplicate Keys

$keys = ['a', 'b', 'a'];
$values = [1, 2, 3];

$result = array_combine($keys, $values);
// Result: ['a' => 3, 'b' => 2]
// Last value overwrites previous

Common Patterns

Safe Combination

function safe_combine($keys, $values) {
    if (count($keys) !== count($values)) {
        throw new InvalidArgumentException('Arrays must have same length');
    }
    
    if (empty($keys)) {
        return [];
    }
    
    return array_combine($keys, $values);
}

Combine with Validation

$keys = ['name', 'email'];
$values = ['John', 'john@example.com'];

if (count($keys) === count($values) && !empty($keys)) {
    $data = array_combine($keys, $values);
    // Use $data
}

Reindex and Combine

$keys = array_values(['a', 'b', 'c']);
$values = array_values([1, 2, 3]);
$result = array_combine($keys, $values);
Advertisement

Real-World Examples

Form Data Processing

$formFields = ['name', 'email', 'phone'];
$formValues = [$_POST['name'], $_POST['email'], $_POST['phone']];

$data = array_combine($formFields, $formValues);
// Result: ['name' => 'John', 'email' => '...', 'phone' => '...']

Database Result Mapping

$columns = ['id', 'name', 'email'];
$row = [1, 'John', 'john@example.com'];

$user = array_combine($columns, $row);
// Result: ['id' => 1, 'name' => 'John', 'email' => 'john@example.com']

Configuration Arrays

$configKeys = ['host', 'port', 'database'];
$configValues = ['localhost', 3306, 'mydb'];

$config = array_combine($configKeys, $configValues);
// Result: ['host' => 'localhost', 'port' => 3306, 'database' => 'mydb']

API Response Mapping

$fieldNames = ['userId', 'userName', 'userEmail'];
$apiResponse = [123, 'John', 'john@example.com'];

$mapped = array_combine($fieldNames, $apiResponse);

Alternative Methods

Using array_merge with array_flip

// Less efficient alternative
$keys = ['a', 'b', 'c'];
$values = [1, 2, 3];

$flipped = array_flip($keys);
$result = array_merge($flipped, array_combine($keys, $values));

Manual Loop

function manual_combine($keys, $values) {
    if (count($keys) !== count($values)) {
        return false;
    }
    
    $result = [];
    foreach ($keys as $index => $key) {
        $result[$key] = $values[$index];
    }
    return $result;
}

Best Practices

  1. Always check array lengths before combining
  2. Handle empty arrays explicitly
  3. Validate input arrays
  4. Use for key-value mapping scenarios
  5. Consider duplicate keys behavior

Conclusion

array_combine() is essential for:

  • Creating associative arrays from separate arrays
  • Mapping keys to values
  • Transforming data structures
  • Processing form/database data

Key Points:

  • Arrays must have same length
  • Returns associative array
  • Handles various key/value types
  • Check lengths before use
  • Understand duplicate key behavior

Mastering array_combine() enhances your PHP array manipulation capabilities.

Advertisement
Mahesh Waghmare

Written by Mahesh Waghmare

I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.

Follow on Twitter

Read Next