split
Split an array into two
Definition
object split(array[any] $array, int $count)
Splits $array
into two, where the first resulting array contains $count
elements, and the second one the remaining elements. The two arrays are returned inside an object with properties first
and last
.
Parameters
array $array
Array to split.
int $count
The count of elements to put into the first array. If $count
is greater than the length of array
, last
will be an empty array. $count
can be a non-positive integer as well, in which case the split is done in the same way as if it was positive, but the arrays first
and last
are switched.
Returns
object
An object with two properties, first
and last
, where the value of the first
is an array consisting of the first $count
elements of $array
, and the value of last
is an array consisting of any remaining elements of $array
.
Examples
{
a: split(`[1, 2, 3]`, `1`),
b: split(`[1, 2, 3]`, `3`),
c: split(`[1, 2, 3]`, `5`),
d: split(`[1, 2, 3]`, `-1`),
e: split(`[1, 2, 3]`, `2.0`), // Error
f: split(`[1, 2, 3]`, `true`), // Error
g: split(`[1, 2, 3]`, `null`) // Error
}
{
"a": {
"first": [1],
"last": [2, 3]
},
"b": {
"first": [1, 2, 3],
"last": []
},
"c": {
"first": [1, 2, 3],
"last": []
},
"d": {
"first": [2, 3],
"last": [1]
}
}
Remarks
Equivalent to {"first": array[:count], "last": array[count:]}
for non-negative indices and {"first": array[-count:], "last": array[:-count]}
for negative indices.
Updated 12 months ago