Home » PHP

PHP array_combine() Function with Example

PHP array_combine() Function: Here, we are going to learn about the array_combine() function with example in PHP.
Submitted by IncludeHelp, on February 08, 2019

PHP array_combine() Function

array_combine() function is an array function in PHP, it is used to create an array with two different arrays, where the first array contains keys and the second array contains values.

Note: Both parameters should have an equal number of elements.

Syntax:

    array_combine(array1, array2) : array

Here, array1 and array2 are two input arrays. Where, array1 contains "keys" and array2 contains "values". It returns a new array with "keys" and "values".

Examples:

    Input:
    $arr1 = array("101", "102", "103", "104", "105");
    $arr2 = array("Amit Shukla", "Abhishek Jain", "Prerana", "Aleesha", "Prem");

    Function call:
    array_combine($arr1, $arr2);

    Output:
    Array
    (
        [101] => Amit Shukla
        [102] => Abhishek Jain
        [103] => Prerana
        [104] => Aleesha
        [105] => Prem
    )

PHP code:

<?php
    //arr1 contains keys
    $arr1 = array("101", "102", "103", "104", "105");
    //arr2 contains values
    $arr2 = array("Amit Shukla", "Abhishek Jain", "Prerana", "Aleesha", "Prem");
    
    //combining arrays
    $std = array_combine($arr1, $arr2);
    //printing
    print_r ($std);
?>

Output

Array
(
    [101] => Amit Shukla
    [102] => Abhishek Jain
    [103] => Prerana
    [104] => Aleesha
    [105] => Prem
)

PHP Code (If number of elements of both arrays is not same)

<?php
    //arr1 contains keys
    $arr1 = array("1", "2", "3");
    //arr2 contains values
    $arr2 = array("Amit", "Abhishek", "Prerana", "Aleesha");
    
    //combining arrays
    $std = array_combine($arr1, $arr2);
    //printing
    print_r ($std);
?>

Output

PHP Warning:  array_combine(): Both parameters should have an equal 
number of elements in /home/main.php on line 8





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.