PHP Array combine() Function
The array_combine() function is an inbuilt function in PHP. This function is introduced in PHP 5. It is used to create an array by using one array for keys and another for its values.
Syntax
array_combine(array_keys,array_values);
Parameters
Parameter | Description | Is compulsory |
---|---|---|
array_keys | The keys of the array to be used | Compulsory |
array_values | The values of the array to be used | Compulsory |
Important note: Total number of elements in both of the arrays must be equal for the function to execute successfully otherwise, it will throw an error.
PHP Example
<?php
$language =array('Php', 'Core java', 'C', 'Javascript', 'C++');
$marks = array(95, 96, 80, 75,68);
$language_marks=array_combine($language, $marks);
print_r($language_marks);
?>
Output
Array ( [Php] => 95 [Core java] => 96 [C] => 80 [Javascript] => 75 [C++] => 68 )
PHP Example
<?php
function Combine($nam1, $age2)
{
return(array_combine($nam1, $age2));
}
$nam1 = array("Ajay", "Amit", "Rahul");
$age2 = array('24', '30', '35');
print_r(Combine($nam1, $age2));
?>
Output
Array ( [Ajay] => 24 [Amit] => 30 [Rahul] => 35 )
PHP Example
<?php
$a1=array("a","b","c","d");
$g2=array("Cricket","Football","Badminton","Hockey");
print_r(array_combine($a1,$g2));
?>
Output
Array ( [a] => Cricket [b] => Football [c] => Badminton [d] => Hockey )
PHP Example
<?php
$a = array('green', 'red', 'yellow');
$b = array('guava', 'cherry', 'orange');
$c = array_combine($a, $b);
print_r($c);
?>
Output
Array ( [green] => guava [red] => cherry [yellow] => orange )