Current Location: Home> Latest Articles> How to combine two arrays into key-value pairs using the array_combine function in PHP?

How to combine two arrays into key-value pairs using the array_combine function in PHP?

M66 2025-05-12

In PHP, the array_combine() function allows you to combine two arrays into an associative array. The value of one array will be used as the key and the value of another array will be used as the value of that key, thus generating a key-value pair. This kind of operation is very useful when processing data, especially when you have two related data sets and want to merge them into a more operational structure.

Basic syntax of array_combine() function

 array_combine(array $keys, array $values): array
  • $keys : an array of keys as new array.

  • $values ​​: an array as the value of the new array.

Requirements for using array_combine()

  • The lengths of the $keys array and the $values ​​array must be the same. If they are of different lengths, the array_combine() function returns FALSE .

  • The value of the $keys array must be a legal key (i.e., it must be a scalar type, such as a string or an integer).

Sample code

 <?php
// Define two arrays,A contains key,Another contains value
$keys = ["apple", "banana", "orange"];
$values = [1, 2, 3];

// use array_combine() Combine two numbers into key-value pairs
$result = array_combine($keys, $values);

// Output result
print_r($result);
?>

Output result

 Array
(
    [apple] => 1
    [banana] => 2
    [orange] => 3
)

In this example, the element of the $keys array becomes the key of the $result array, and the element of the $values ​​array becomes the value of the corresponding key. In this way, array_combine() combines these two arrays into an associative array.

Process arrays of different lengths

If the two arrays have different lengths, array_combine() returns FALSE . For example:

 <?php
$keys = ["apple", "banana"];
$values = [1, 2, 3];

$result = array_combine($keys, $values);

// If the array length is not consistent,return FALSE
if ($result === FALSE) {
    echo "Error: Arrays have different lengths.";
}
?>

in conclusion

The array_combine() function is a very practical tool in PHP that helps you easily combine two arrays into an associative array. Just make sure that the two arrays are the same length, you can convert them into key-value pairs smoothly. This function is very convenient when processing data, especially when it is necessary to match certain lists with their corresponding values.