PHP Array array_combine() Function (With Examples)

In this tutorial, we will learn about the PHP array_combine() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_combine() Function

The 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

The syntax of the array_combine() function:

array_combine(array1, array2) : array

Parameters

The parameters of the array_combine() function:

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

Return Value

The return type of this method is array, it returns the combined array.

Sample Input/Output

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 array_combine() Function Example 1

<?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

The output of the above example is:

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

PHP array_combine() Function Example 2

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

The output of the above example is:

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

To understand the above example, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.