Split can be used to split an array into two arrays where the split is made on a defined position. The output of the function is an object containing the two new arrays.
Syntax
json_object split(array $input, integer $count)
Splits $input into two arrays called “first” and “last” and outputs these in a json object. $count is the number of elements that should be put in the “first” array and the “last” array contains the rest of the elements.
Parameters
$input: The array that should be split into two.
$count: The number of elements that should be in the first array.
Example
{
"Array": [1,2,3,4,5,6]
}
{
Splitted: split(Array, `4`)
}
{
"Splitted": {
"first": [1,2,3,4],
"last": [5,6]
}
}
Above example splits the array of integers on the 4th position (starting from 1) and puts the 4 first elements of the array in the “first” array and the rest of the elements in the “last” array.
Notes
Available types
The $input array can contain any type (integer, string, object, array, etc.)
The $count integer can be both positive and negative numbers with followings rules:
- If $count is 0 (Zero) it will return all elements in the “first” array and the “last” array will be empty.
- If $count is less than 0 (Negative) it will populate the “last” array first and put the rest of the elements in the “first” array.
- If $count is larger than 0 (Positive) it will pupulate the “first” array first and put the rest of the elements in the “last” array.
- If $count is larger (LargerPositive / LargerNegative) than the length of the array all of the elements will be put in either the “first” or “last” array depending on whether it is positive or negative respectively and the other array will be empty.
More examples
{
Zero: split(Array, `0`),
Negative: split(Array, `-4`),
Postive: split(Array, `4`),
LargerPositive: split(Array, `10`),
LargerNegative: split(Array, `-10`)
}
{
"Zero": {
"first": [1,2,3,4,5,6],
"last": []
},
"Negative": {
"first": [5,6],
"last": [1,2,3,4]
},
"Postive": {
"first": [1,2,3,4],
"last": [4,5,6]
},
"LargerPositive": {
"first": [1,2,3,4,5,6],
"last": []
},
"LargerNegative": {
"first": [],
"last": [1,2,3,4,5,6]
}
}