PHP array_combine() Function
The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values. That is all elements of one array will be the keys of new array and all elements of the second array will be the values of this new array.
Syntax
array_combine( $keys_array, $values_array )
Parameters
This function accepts two parameters and both are mandatory. The function parameters as listed below:
- $keys_array: This is an array of keys. If illegal values are passed as the key, then it will be converted into a string.
- $values_array: This is an array of values that is to be used in the new array.
Return Value
The array_combine() function returns a new associative array where the keys are taken from the first array ($keys_array), and the values are taken from the second array ($values_array). If the two arrays have different lengths, the function will return false and raise a warning.
Example 1: Combining Two Arrays
<?php
$array1 = array("Ram", "Akash", "Rishav");
$array2 = array('24', '30', '45');
$result = array_combine($array1, $array2);
print_r($result);
?>
Output
Array ( [Ram] => 24 [Akash] => 30 [Rishav] => 45 )
Note: The total number of elements in both of the arrays must be equal for the function to execute successfully otherwise it will throw an error.
Example 2: Using Numbers as Keys and Values
<?php
$array1 = array("65824", "92547", "12045");
$array2 = array('1', '2', '3');
$result = array_combine($array1, $array2);
print_r($result);
?>
Output
Array ( [65824] => 1 [92547] => 2 [12045] => 3 )
Reference: https://www.php.net/manual/en/function.array-combine.php