PHP array_combine() Function

What is PHP array_combine() Function?

Combining two arrays, PHP array_combine() function creates one array. The function uses the values of the first array to create keys and the values of the second array to create values of the resulting array. The two arrays may be the same array or different ones.

Syntax:

array_combine(array_of_keys, array_of_values)

Parameters:

The Function has 2 required parameters –

array_of_keys (Required): It is an array whose values will be converted to keys of the new array.

array_of_values (Required): It is an array whose values will be converted to values of the new array.

Return Values:

The function returns-

  • A new array combining values of two arrays if the number of elements in both arrays are same. Check example 1.
  • A ValueError (as of PHP 8.0.0) or a E_WARNING (prior to PHP 8.0.0) if the number of elements in both arrays are not same. Check example 2.

Examples:

Example 1:

<pre>
<?php
$keys = [0, 1, 2, 3];
$values = ['PHP', 'Python', 'Java', 'Ruby'];
$array = array_combine($keys, $values);
print_r($array);
?>
</pre>

Output:

Array
(
    [0] => PHP
    [1] => Python
    [2] => Java
    [3] => Ruby
)

Example 2:

<pre>
<?php
$keys = [0, 1, 2, 3];
$values = ['PHP', 'Python', 'Java'];
$array = array_combine($keys, $values);
print_r($array);
?>
</pre>

Output:

Fatal error:  Uncaught ValueError: array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements in D:\xampp\htdocs\array_combine function.php:3Stack trace:#0 D:\xampp\htdocs\array_combine function.php(3): array_combine(Array, Array)#1 {main}  thrown in D:\xampp\htdocs\array_combine function.php on line 3

PHP Version Support:

PHP 5, PHP 7, PHP 8

Summary: PHP array_combine() Function

array_combine() is a very useful function to combine two arrays – one for creating keys and the other for creating values for the resulting array. It is one of powerful built-in PHP array functions.

Reference:

https://www.php.net/manual/en/function.array-combine.php