How To Use Array Combine Function With Example In PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

The array combine creates an array by using the elements from one "keys" array and one "values" array.it will combine all elements to makes one array and both array should have equal number of elements.

combine_array

The array_combine() is an inbuilt function  which is helps to combine two arrays and create a new array by using one array for keys and another array for values. 


Syntax of array_combine function and Usage:

array_combine(keys, values)
 

Parameter Description:

Parameter        Description
keys             Array of keys
values           Array of values
 

1.Create first array.

$array1 =array("Seetha", "Radha", "neha");
 

2.Create second array.

$array2 =array(34, 32,27);

 

3.Now use array combine function to combine $array1 and $array2

$new_array=array_combine($array1,$array2);

 

4.print $new_array using print_r or you can also use foreach loop.

print_r($new_array);

 

5.Complete code for an array_combine function.

<!DOCTYPE html>
<html>
<head>
    <title>Combine arrays in PHP</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>Combine arrays in PHP</h1>
    </div>
    <br>
    <h2></h2>
    <div class="well">
        <?php
        $array1 = array("1", "2", "3");
        $array2 = array("Seetha","Radha","Neha");
        $new_array=array_combine($array1,$array2);
        print_r($new_array);
        foreach($new_array as $new){
            echo "<h4>".$new."</h4>";
        }
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post