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
  • Calculate the intersection of the array and compare the data using the callback function array_uintersect

    array_uintersect

    Calculatetheintersec
  • Reverse sorting of arrays rsort

    rsort

    Reversesortingofarra
  • Sort arrays using the "natural sort" algorithm natsort

    natsort

    Sortarraysusingthe&q
  • Move the inner pointer in the array one by one next

    next

    Movetheinnerpointeri
  • Alias ​​for current pos

    pos

    Alias​​forcurrent
  • Check if there is a value in the array in_array

    in_array

    Checkifthereisavalue
  • Returns the value of a single column in the input array array_column

    array_column

    Returnsthevalueofasi
  • Rewind the inner pointer of the array back to one prev

    prev

    Rewindtheinnerpointe