Learn how to easily split a string by a delimiter and convert it to an array.

Twig offers a lot of filters that replicate basic features of PHP that are as well easy to understand to front-end developers. One of those filters is the split filter that allows you to split a string delimited by a character, returning an iterable array:

{% set tags = "First,Second,Third"|split(",") %}
{# tags contains ['First', 'Second', 'Third'] #}

{# Print every tag in a new line #}
{% for tag in tags %}
    {{ tag }}
{% endfor %}

You can limit the length of the result array providing it as second argument, for example, to limit the length of the array to only 3 items:

{% set tags = "first,second,third,fourth,fifth"|split(',', 3) %}
{# tags contains ["first", "second", "third,fourth,fifth"]#}

{% for tag in tags %}
    {{ tag }}
{% endfor %}

If the delimiter is empty, the string will be split into chunks of the same size:

{% set tags = "abcd"|split('') %}
{# tags contains ["a", "b", "c", "d"]#}

{% for tag in tags %}
    {{ tag }}
{% endfor %}

Whenever there's no delimiter (an empty string), the limit argument will specify the size of the chunk:

{% set tags = "aabbccdd"|split('', 2) %}
{# tags contains ["aa", "bb", "cc", "dd"]#}

{% for tag in tags %}
    {{ tag }}
{% endfor %}

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors