Last Updated on August 10, 2021 by Roshan Parihar
PHP array_combine() Function is used to combine two arrays in which it creates keys from one array and values from another array. It uses one array for keys and another array for values to create a new array in PHP.
Let’s find out the use of the array_combine()
with the examples given below.
Syntax of PHP array_combine() Function
The function takes two arguments to create a new array in PHP by combining them. The first argument is the array to take keys and the second argument is the array to take values for the new array.
Description of Parameters
Name | Description |
---|---|
keys | Required. It is the array to use for creating the keys for the new array. |
values | Required. Specify the array to take its elements as the values of the new array in PHP. |
Let’s see some examples that are useful to understand the use of the PHP array_combine()
Function in PHP.
Examples of PHP array_combine() Function
See the different examples to learn all the uses of the array_combine()
Function in PHP.
Example 1: Combine an array of subjects with marks
Suppose you have subjects and marks in separate arrays but in proper sequence. You can combine each subject with its marks using the array_combine()
Function of PHP. After the use of the function, you can easily get the marks for the required subject.
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare an array in PHP $myarray1 = array("English", "Maths", "Science", "Physics"); $myarray2 = array(69, 93, 73, 71); //Combine two array as keys and values $newArr = array_combine($myarray1, $myarray2); //Print result print_r($newArr); ?> |
Output
The above output shows the new array that contains subject names in combination with the marks.
Example 2: Marge Age of Persons
If you have a number of people and their ages in different array but in proper sequence. You can easily merge them using the function. It gives the resulted array that is useful to easily identify the age of the person.
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare an array in PHP $myarray1 = array("Ram", "Kishore", "Bhanu", "Bill"); $myarray2 = array(28, 31, 25, 19); //Combine two array as keys and values $newArr = array_combine($myarray1, $myarray2); //Print result print_r($newArr); ?> |
Output
The new array given in the output above contains the new array. The resulted array makes it easier to find the age of the person.
You May Also Like to Read