array_merge() / array_combine() Since: PHP 4(2000)
Functions for merging multiple arrays or creating an associative array from separate key and value arrays.
Syntax
// Merges multiple arrays into one. array_merge(array1, array2, ...); // Creates an associative array from a keys array and a values array. array_combine(keys_array, values_array); // Splits an array into chunks of a specified size. array_chunk(array, size, preserve_keys);
Function List
| Function | Description |
|---|---|
| array_merge($array1, $array2, ...) | Merges multiple arrays into a single array. Duplicate string keys are overwritten by the later value; numeric keys are re-indexed from zero. |
| array_combine($keys, $values) | Creates an associative array using one array as keys and another as values. Returns an error if the two arrays have different numbers of elements. |
| array_chunk($array, $size, $preserve_keys) | Splits an array into chunks of the specified size and returns a two-dimensional array. |
Sample Code
<?php // Merge two arrays into one. $front = ['HTML', 'CSS', 'JavaScript']; $back = ['PHP', 'Python', 'Ruby']; $all = array_merge($front, $back); print_r($all); // All 6 elements are combined into a single array. // When merging associative arrays, duplicate keys are overwritten by the later value. $defaults = ['color' => 'white', 'size' => 'M', 'stock' => 10]; $custom = ['color' => 'red', 'stock' => 5]; $result = array_merge($defaults, $custom); print_r($result); // 'color' is overwritten with 'red', 'stock' with 5. // Create an associative array from a keys array and a values array. $names = ['Taro', 'Hanako', 'Jiro']; $ages = [25, 30, 20]; $users = array_combine($names, $ages); print_r($users); // Results in an associative array keyed by name. // Split an array into chunks of 3. $numbers = [1, 2, 3, 4, 5, 6, 7]; $chunks = array_chunk($numbers, 3); print_r($chunks); // Results in a two-dimensional array with up to 3 elements each.
Notes
array_merge() is the most commonly used array merging function. When duplicate string keys exist in associative arrays, the later array's value overwrites the earlier one — making it useful for patterns like applying user settings on top of defaults. For numeric keys, values are never overwritten; all elements are appended and re-indexed starting from zero.
In PHP 7.4 and later, you can also merge arrays using the spread operator: [...$array1, ...$array2]. This syntax can be more intuitive and readable in some cases.
array_combine() requires both arrays to have the same number of elements; a ValueError is thrown if they differ. A common use case is processing CSV data by using the header row as keys and a data row as values.
array_chunk() is handy for implementing pagination or batch processing where you need to handle data in fixed-size groups. For retrieving array keys and values, see array_keys() / array_values().
If you find any errors or copyright issues, please contact us.