php.array_combine()
In this tutorial, we will learn how we can combine two arrays using the built-in array_combine()
function from PHP standard library.
The PHP array_combine() function allows you to combine two arrays by using one array for the keys and the other arrays for its values.
Function Syntax
The following shows the function definition for the array_combine()
function.
array_combine(array $keys, array $values): array
Function Parameters
The function accepts two main parameters as described below:
keys
- this parameter denotes the array to be used as the keys. Illegal values for the keys will be converted to string type.values
- this parameter determines the array to be used for the values.
Function Return Value
The function returns a combined array with the input values converted to keys and values.
NOTE: The function will return a ValueError
if the the number of elements and values do not match.
Examples
Let us look at some basic examples of how to work with the array_combine()
function.
Example 1
The following is a basic example of how to use the array_combine()
function to join two arrays together.
$keys = array('red', 'green', 'blue');
$values = array('#FF0000', '#00FF00', '#0000FF');
$colors = array_combine($keys, $values);
print_r($colors);
This should return an output as shown:
Array
(
[red] => #FF0000
[green] => #00FF00
[blue] => #0000FF
)
This example demonstrates how to use the array_combine()
method to combine array with color names tot heir corresponding hex codes.
Conclusion
In this post, we explored how we can use the array_combine()
method to combine two arrays by using one array for keys and the other array as values.