Home > Article > Backend Development > How to merge and split PHP arrays
PHP array is a very commonly used data structure, and the merging and splitting operations of arrays are often involved in development. This article will introduce how to use PHP language to implement these two operations, and attach corresponding code examples.
1. Merge arrays
The operation of merging arrays can be implemented using the array_merge() function. This function accepts multiple arrays as arguments and merges them into a new array.
Code example:
$array1 = ["apple", "banana"]; $array2 = ["orange", "grape"]; $mergedArray = array_merge($array1, $array2); print_r($mergedArray);
Output result:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
In the above code example, we define two arrays $array1 and $array2 and use the array_merge() function Merge them into a new array $mergedArray. Finally, use the print_r() function to print the output results.
2. Split the array
The operation of splitting the array can be implemented using the array_chunk() function. This function accepts two parameters, the first parameter is the array to be divided, and the second parameter is the number of elements contained in each divided subarray.
Code example:
$array = ["apple", "banana", "orange", "grape", "melon"]; $chunks = array_chunk($array, 2); print_r($chunks);
Output result:
Array ( [0] => Array ( [0] => apple [1] => banana ) [1] => Array ( [0] => orange [1] => grape ) [2] => Array ( [0] => melon ) )
In the above code example, we define an array $array and use the array_chunk() function to split it into A subarray containing two elements. Finally, use the print_r() function to print the output results.
Summary:
This article introduces how to use PHP language to implement array merging and splitting operations. The array_merge() function can be used to merge multiple arrays into a new array, and the array_chunk() function can be used to split an array into multiple sub-arrays containing a specified number of elements. These two operations are very common in development and are very useful for processing array data. I hope the code examples in this article can be helpful to everyone in development.
The above is the detailed content of How to merge and split PHP arrays. For more information, please follow other related articles on the PHP Chinese website!