2

Im looping over an array of objects, and then trying to split one of the elements, in this case I want to split the postcode on the space. Ie. 'AB1 1AB' should just be 'AB1' .

{% for result in resultset %}
            {{ result.postcode|split(' ') }}
    {% endfor %}

Throws me an 'array to string error'

Trying just:

{{ result.postcode[0] }}

Throws me a 'impossible to access key [0] on a string varaible' error.

and just doing:

{{ result.postcode }}   

gives me no error, with the postcode displayed as 'AB1 1AB'

Why does Twig think the string is an array when I try to split it?

2 Answers 2

4

From the official doc:

The split filter splits a string by the given delimiter and returns a list of strings:

{{ "one,two,three"|split(',') }}
{# returns ['one', 'two', 'three'] #}

So, taking your code, you could do something like:

{% for result in resultset %}
    {{ set myArray = result.postcode|split(' ') }}
    {{ myArray[0] }} {# Will output "AB1" #}
{% endfor %}

Source: TWIG Split filter

Sign up to request clarification or add additional context in comments.

3 Comments

I just figured this out myself (14 seconds after you posted this) Always the way. :) While this works, I don't really understand why. How is result.postcode considered an array, when it can be outputted as a string?
result.postcode is a string. But if you split it, the returned object is a list of string. So, if you take that into a variable (like myArray) you'll be able to display all the array values (the result of the split), which are myArray[0] => "AB1" and myArray[1] => "1AB". I hope I've helped you :)
Thanks for your help. From the Twig docs: Internally, Twig uses the PHP explode which - from the PHP docs - Returns an array of strings , not a list of strings. Confusing! There we go though.
1

It's an old question but the real problem is that you asked Twig to display the result of your split using a {{...}} block. You should use the {%...%} block and set tag, as explained in the documentation.

If you only want to display some part, you can use either split with [first][2] filter or slice.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.