0
0
PhpHow-ToBeginner · 3 min read

How to Use array_combine in PHP: Syntax and Examples

Use array_combine in PHP to create a new array by using one array for keys and another for values. Both arrays must have the same number of elements, or the function will return false.
📐

Syntax

The array_combine function takes two arrays: one for keys and one for values, and returns a new array combining them.

  • keys: An array of keys for the new array.
  • values: An array of values corresponding to each key.

Both arrays must have the same number of elements.

php
array_combine(array $keys, array $values): array|false
💻

Example

This example shows how to combine two arrays into one associative array where the first array provides keys and the second provides values.

php
<?php
$keys = ['name', 'age', 'city'];
$values = ['Alice', 25, 'New York'];

$combined = array_combine($keys, $values);
print_r($combined);
?>
Output
Array ( [name] => Alice [age] => 25 [city] => New York )
⚠️

Common Pitfalls

Common mistakes include:

  • Using arrays of different lengths, which causes array_combine to return false.
  • Passing empty arrays, which also returns false.

Always check the return value before using the result.

php
<?php
// Wrong: different lengths
$keys = ['a', 'b'];
$values = [1];
$result = array_combine($keys, $values);
var_dump($result); // bool(false)

// Right: same lengths
$values = [1, 2];
$result = array_combine($keys, $values);
print_r($result);
?>
Output
bool(false) Array ( [a] => 1 [b] => 2 )
📊

Quick Reference

ParameterDescription
keysArray of keys for the new array
valuesArray of values for the new array
ReturnNew combined array or false if input arrays differ in size

Key Takeaways

array_combine creates an associative array from two arrays: keys and values.
Both input arrays must have the same number of elements or it returns false.
Always check the return value to avoid errors with mismatched arrays.
Empty arrays passed to array_combine will return false.
Use array_combine to quickly pair related data into key-value form.