Current Location: Home> Function Categories> array_combine

array_combine

Create an array by using one array as key and another as its value
Name:array_combine
Category:Array
Programming Language:php
One-line Description:Create a new array by merging two arrays.

array_combine function

Applicable to PHP version

PHP 4 >= 4.0.0, PHP 5, PHP 7, PHP 8

Function description

The array_combine function combines two arrays into an associative array, the value of the first array is used as the key, and the value of the second array is used as the corresponding value. The number of elements in the array must be the same, otherwise an error will be triggered.

Function Syntax

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

parameter

  • $keys : an array containing the elements to be used as keys.
  • $values : an array containing the elements to be used as values.

Return value

Returns an array containing key-value pairs, and if the input array length is different, returns FALSE.

Example

<?php
$keys = ["a", "b", "c"];
$values = [1, 2, 3];
$result = array_combine($keys, $values);
<p>print_r($result);<br>
?><br>

Description of sample code

In this example, we create two arrays: $keys and $values. By calling the array_combine function, the elements in the $keys array are used as keys and the elements in the $values array are used as values, and finally a associative array $result is returned. The output result will be:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Note: If the lengths of the $keys and $values arrays are not equal, the function returns FALSE. For example:

<?php
$keys = ["a", "b"];
$values = [1, 2, 3];
$result = array_combine($keys, $values);
<p>var_dump($result);<br>
?><br>

The above code will output:

 bool(false)
Similar Functions