English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP array_combine() Function Usage and Example

PHP Array Function Manual

Definition and Usage

array_combine()The function combines two arrays into one array, using two different or the same arrays as input, and creates a new array by using the values in the keys array as keys and the values in the values array as corresponding values.

When passing two arrays to this function,}}Please make sure that the number of elements in the two arrays is equal, otherwise an error will be returned.

Syntax

array array_combine(array $keys, array $values);

Parameter

Serial NumberParameters and Description
1number

keys (required)

the first array, whose values are used as the keys of the new array.

2

values (required)

the second array, whose values are used as the values of the new array.

Return Value

The PHP array_combine() function returns a combined array, otherwise, if the number of elements in each array is not equal or the array is empty, it returnsFALSE.

PHP version

This function was originally introduced in PHP version5introduced in version .0.0.

Error/Exception

If the number of elements in the key and value arrays does not match, an E_WARNING is thrown.

Online Example

The following is an example of using two different arrays to combine them into an array-

<?php
   $a = array('green', 'red', 'yellow');
   $b = array('avocado', 'apple', 'banana');
   $c = array_combine($a, $b);
   print_r($c);
?>
Test and see‹/›

Output Result

Array
(
    [green] => avocado
    [red] => apple
    [yellow] => banana
)

Online Example

The following is an example of using two different arrays to combine them into an array, but this time we use unequal numbers of elements in both arrays-

<?php
   $a = array('green', 'red', 'yellow');
   $b = array('avocado', 'apple');
   $c = array_combine($a, $b);
   print_r($c);
?>
Test and see‹/›

Output Result

PHP Warning: Both parameters should have an equal number of elements in main.php on line 4

Online Example

If two keys are the same, the second one is used.-

<?php
   $a = array('green', 'green', 'yellow');
   $b = array('avocado', 'apple', 'banana');
   $c = array_combine($a, $b);
   print_r($c);
?>
Test and see‹/›

Output Result

Array
(
    [green] => apple
    [yellow] => banana
)

Online Example

We can use the same input array to create a new array. Try the following example-

<?php
   $a = array('green', 'green', 'yellow');
   $c = array_combine($a, $a);
   print_r($c);
?>
Test and see‹/›

Output Result

Array
(
    [green] => green
    [yellow] => yellow
)

PHP Array Function Manual