Merging Arrays as Key-Value Pairs in PHP: A Simple Technique
When working with arrays in PHP, it often becomes necessary to merge two arrays while establishing a key-value relationship between the elements. While manual looping is a viable approach, let's explore a more efficient method.
Solution: array_combine()
PHP provides a built-in function, array_combine(), specifically designed for this purpose. This function takes two arrays as arguments:
array_combine() merges the two arrays, creating a new array where the elements from the first array are used as keys, and the corresponding elements from the second array are assigned as values.
Example:
Consider the following arrays:
$keys = ['name', 'age', 'gender']; $values = ['John', 25, 'Male'];
To merge these arrays using array_combine():
$key_value_pairs = array_combine($keys, $values);
The resulting array, $key_value_pairs, will look like this:
['name' => 'John', 'age' => 25, 'gender' => 'Male']
As you can see, the keys from the first array ($keys) have been mapped to the values from the second array ($values). This provides a quick and concise way to establish key-value relationships between the elements of two arrays.
The above is the detailed content of How Can I Efficiently Merge Two PHP Arrays into Key-Value Pairs?. For more information, please follow other related articles on the PHP Chinese website!