English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
array array_combine(array $keys, array $values);
Serial Number | Parameters 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. |
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.
This function was originally introduced in PHP version5introduced in version .0.0.
If the number of elements in the key and value arrays does not match, an E_WARNING is thrown.
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 )
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
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 )
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 )