Chunk ViewHelper <f:chunk> 

The ChunkViewHelper splits an array or a string into chunks of the given size. The last chunk may be shorter if the items or characters can't be divided evenly.

For arrays, this ViewHelper mimicks PHP's array_chunk() function. For strings, it mimicks PHP's mb_str_split() function, so the size counts characters, not bytes.

Iterators like generators can yield the same key more than once. All of their items are used, unless preserveKeys is set: then only the last item per key is used, like with PHP's iterator_to_array() function.

Examples 

Split an array into chunks 

Given items = ['a', 'b', 'c', 'd', 'e']:

<f:chunk value="{items}" size="2" />
Copied!
[
    ['a', 'b'],
    ['c', 'd'],
    ['e'],
]
Copied!

Preserve the original array keys 

Given scores = ['a' => 1, 'b' => 2, 'c' => 3]:

<f:chunk value="{scores}" size="2" preserveKeys="{true}" />
Copied!
[
    ['a' => 1, 'b' => 2],
    ['c' => 3],
]
Copied!

Render items in rows 

<f:for each="{items -> f:chunk(size: 2)}" as="row">
    <div class="row"><f:for each="{row}" as="item"><span>{item}</span></f:for></div>
</f:for>
Copied!
<div class="row"><span>a</span><span>b</span></div>
<div class="row"><span>c</span><span>d</span></div>
<div class="row"><span>e</span></div>
Copied!

Split a string into groups 

Given iban = 'DE89370400440532013000':

{iban -> f:chunk(size: 4) -> f:join(separator: ' ')}
Copied!
DE89 3704 0044 0532 0130 00
Copied!

Go to the source code of this ViewHelper: ChunkViewHelper.php (GitHub).

Arguments

The following arguments are available for the chunk ViewHelper:

preserveKeys

preserveKeys
Type
boolean
Default
false
If true, the keys of the original array are preserved in each chunk. Otherwise each chunk is reindexed numerically. Has no effect on strings.

size

size
Type
integer
Required
1
Number of items or characters in each chunk. The last chunk may be shorter.

value

value
Type
mixed
The array or string to split into chunks