To join arrays in PHP, we have a ready-made function that can be used, that is the array_splice() function, which will delete all elements from the array starting at offset to ending at offset+length, and return it in the form of an array The deleted element. The syntax format of array_splice() is:
array array_splice (array array, int offset[,length[,array replacement]])
When offset is a positive value, the joining will start from the offset position from the beginning of the array. When offset is a negative value, the joining will start from the offset position from the end of the array. If the optional length parameter is omitted, all elements starting at offset position and ending at the end of the array will be removed. If length is given and is positive, the join ends at offset + leng th from the beginning of the array. Conversely, if length is given and is negative, the union will end count(input_array)-length from the beginning of the array.
Let’s look at a standard example of joining arrays, PHP code:
1
2$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
3$subset = array_splice($fruits, 4);
4print_r($fruits);
5print_r($subset);
6//The output result is:
7// Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Pear )
8// Array ( [0] => Grape [1] => Lemon [2] => Watermelon )
9?>
We can also use the optional parameter replacement to specify the array to replace the target part. Please see the example below:
1
2$fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
3$subset = array_splice($fruits, 2, -1, array("Green Apple", "Red Apple"));
4print_r($fruits);
5print_r($subset);
6// Output result:
7// Array ( [0] => Apple [1] => Banana [2] => Green Apple [3] => Red Apple [4] => Watermelon )
8// Array ( [0] => Orange [1] => Pear [2] => Grape [3] => Lemon )
9?>
of the array