PHP array_combine() function
The array_combine()
function in PHP is used to create a new array by combining two arrays: one for keys and one for values. This function is particularly useful when you have two separate arrays that you want to merge into a single associative array, where one array contains the keys and the other contains the corresponding values.
Syntax:
Parameters:
- $keys: An array of keys. This array must contain unique values, as duplicate keys will result in an error.
- $values: An array of values that correspond to the keys. This array must have the same number of elements as the keys array; otherwise, the function will return
false
.
Return Value:
- The function returns a new associative array where each key from the
$keys
array is paired with the corresponding value from the$values
array. If the input arrays do not have the same number of elements or if the keys array contains duplicate keys, it returnsfalse
.
Example 1: Basic Usage
Here’s a simple example demonstrating how to use array_combine()
:
Output:
In this example, the keys
array is combined with the values
array to create an associative array.
Example 2: Different Lengths
If the $keys
and $values
arrays have different lengths, the function will return false
.
Output:
Example 3: Duplicate Keys
If the $keys
array contains duplicate values, an error will occur.
Output:
Example 4: Using Numeric Keys
You can also use numeric keys with array_combine()
.
Output:
Practical Usage:
- The
array_combine()
function is useful in various scenarios, such as:- Creating associative arrays from two separate datasets.
- Merging data from different sources where keys and values are provided separately.
- Preparing structured data for further processing or output.
Summary:
array_combine($keys, $values)
creates a new associative array from two input arrays: one for keys and one for values.- The function requires both input arrays to have the same number of elements and ensures that keys are unique.
- It simplifies the process of transforming two separate lists into a structured associative array, making data handling more efficient in PHP applications.