At times, it is necessary to ensure that an array contains an exact number of entries at all times, even if the data for this does not exist in the payload. Using take_or_default
allows a user to define the exact length of an array, and the default value that should be appended to the array for each item that is missing.
Syntax
array take_or_default(array $array, integer $count, any $default)
Appends $default
values to an $array
where necessary to ensure that the array length is equal to $count
.
Parameters
$array: The input array.
$count: The exact length that the output array should be.
$default: The default value that should be added to the array for each item that is missing.
Example
{
"AvailableUsers": [
"Todd",
"Bob",
"Steve"
]
}
{
listOfUsers: take_or_default(AvailableUsers, '6', 'Unconfirmed User')
}
{
"listOfUsers": [
"Todd",
"Bob",
"Steve",
"Unconfirmed User",
"Unconfirmed User",
"Unconfirmed User"
]
}
In this example the input $array
contains only 3 items but the transformation defines that the listOfUsers
array in the result should have a length of 6 so 3 additional “Unconfirmed User” entries are appended to the original array.
Notes
The resulting array will ALWAYS have a length equal to $count
. So if the input $array
is already equal to or greater than the $count
defined in the transformation then the resulting array will be truncated appropriately.
For example, if the transformation above was altered to have a count of 2 then the resulting array would show only the first two entries of the input $array
and no default values would be appended.
{
listOfUsers: take_or_default(AvailableUsers, '2', 'Unconfirmed User')
}
{
"listOfUsers": [
"Todd",
"Bob"
]
}