PHP array_combine() function is “used to combine two arrays and create a new array by using one array for keys and another array for values.”
The number of elements in both arrays must be equal, as the function returns false if the number of elements does not match.
Syntax
array_combine(keys,values);
Parameters
- keys: It is required and an array of keys.
- values: It is required, and it is an array of values.
Return value
It returns a new combined array, in which the elements from the first array $keys_array represent keys in the new array, and the elements from the second array $values_array represent the corresponding values in the new array.
Visual Representation
Example 1: How to Use array_combine() function
<?php
$superHeros = ['Ironman', 'Thor', 'Captain America'];
$characterNames = ['Tony Stark', 'Thor', 'Steve Rogers'];
$finalArray = array_combine($superHeros, $characterNames);
print_r($finalArray);
Output
Array
(
[Ironman] => Tony Stark
[Thor] => Thor
[Captain America] => Steve Rogers
)
In this example, three keys Ironman, Thor, and Captain America are combined with the values Tony Stark, Thor, and Steve Rogers. The resulting array $finalArray uses Ironman, Thor, and Captain America as keys for the respective values.
Example 2: If two keys are the same
<?php
$x = ['a', 'b', 'b', 'c'];
$y = ['A', 'B', 'K', 'C'];
$finalArray = array_combine($x, $y);
print_r($finalArray);
Output
Array
(
[a] => A
[b] => K
[c] => C
)
In PHP, array keys must be unique. If there are duplicate keys in $a array (In the above example, ‘b’ appears twice), only the last key-value pair is used, with earlier occurrences being overwritten.
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.