take_or_default

Get the first part of the array

Definition

array[any] take_or_default(array[any] $array, int $count, any $defaultValue))

Returns the subarray of $array consisting of the first $count elements. If $count is greater than the length of $array, pads the array with as many instances of $defaultValue as needed to ensure the returned array has length equal to $count.

Parameters

array $array

Array to take from.

int $count

The desired length of the return array.

any $defaultValue

The value to fill out the return array with in case $count is greater than the length of $array.

Returns

array

Array consisting of the first $count elements of $array. In case $count is greater than the length of $array, the entire $array is included, and the rest of the elements are set to $defaultValue to reach the final length of $count.

Examples

{
  a: take_or_default(`[1, 2, 3]`, `1`, `null`),
  b: take_or_default(`[1, 2, 3]`, `3`, `null`),
  c: take_or_default(`[1, 2, 3]`, `5`, `null`),
  d: take_or_default(`[1, 2, 3]`, `-1`, `null`),
  e: take_or_default(`[1, 2, 3]`, `2.0`, `null`),
  f: take_or_default(`[1, 2, 3]`, `true`, `null`),
  g: take_or_default(`[1, 2, 3]`, `null`, `null`)
}
{
  "a": [1],
  "b": [1, 2, 3],
  "c": [1, 2, 3, null, null],
  "d": [],
  "e": [1, 2],
  "f": [1],
  "g": []
}