Thursday, 4 January 2018

array_combine() Function | PHP

Tags

This inbuilt function of PHP  is used to combine two array. array_combine() function combine two arrays and create a new array by using one array for key and another array for value. It means all the elements of first array will be keys and all the elements of the second array will be value of those respective keys. PHP program to explain the use of array_combine() function is given below.

EXAMPLE:

Input: $array1=("Sachin","Rahane","Virat");
            $array2=("80","70","90");

Output:  Array ( [Sachin]=>80 [Rahane]=>70 ["Virat"]=>90)

Syntax:
array_combine ($keys, $values)

This function takes two parameters and both the parameters are mandatory and this function only accepts arrays.

1. Parameter 1: The first parameter will be an array of keys. If values passed are illegal then it will be converted to a string.
2. Parameter 2: The second parameter will be an array of values for the keys passed in the parameter 1.

PROGRAM:


<?php


function combine_two_arrays($array1,$array2){
  
       return(array_combine($array1,$array2));
  
}


//Driver code of the program

$array1=array("Sachin","Rahane","Virat");


echo nl2br("The elements of first array are given below: \r\n");
print_r($array1);

$array2=array(50,90,80);

echo nl2br("\r\n \r\n The elements of second array are given below: \r\n");
print_r($array2);

echo nl2br("\r\n \r\n The comined array is given below: \r\n");
print_r(combine_two_arrays($array1,$array2));

?>

OUTPUT:





EmoticonEmoticon