I am looking for how to trim each string in an array, in Craft 3.

I would like to check if a string is in an array of strings. The array is from a form submission, a checkbox group.

For example, there are two checkboxes and both of them are checked.

{% set array_checked_values = submission|split(',') %}

A: {{ array_checked_values[0] == "Value A" }}
B: {{ array_checked_values[1] == "Value B" }}

Although I do not know why, only A returns true, but B is false.

However, it returns true.

B': {{ array_checked_values[1]|trim == "Value B" }}

So, I need to trim each string in the array, but I do not know how to do that. None of these three method work.

{% set array_checked_values = submission|split(',')|trim %}

{% set array_checked_values = array_checked_values|trim %}

{% for val in array_checked_values %}
    {% set val = val|trim %}
{% endfor %}

2 Answers 2


The other way is you can use array map for this.

{% set array_checked_values = submission|split(',')|map(c => c|trim) %}
  • Thank you very much, it works well and simpler than my code.
    – Kota.M
    Commented Sep 7, 2022 at 18:39

I have resolved it by myself. Although it will be an roundabout way, create another array. When each of the values is migrated, the string can be trimmed.

{% set array_checked_values = submission[field.handle]|split(',') %}
{% set array_checked_values_2 = [] %}

{% for val in array_checked_values %}
    {% set array_checked_values_2 = array_checked_values_2|merge([val|trim]) %}
{% endfor %}

Then, both A and B above return true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.