Check if variable is string or array in Twig

Can be done with the test iterable, added in twig1.7, as Wouter J stated in the comment :

{# evaluates to true if the users variable is iterable #}
{% if users is iterable %}
    {% for user in users %}
        Hello {{ user }}!
    {% endfor %}
{% else %}
    {# users is probably a string #}
    Hello {{ users }}!
{% endif %}

Reference : iterable


Ok, I did it with:

{% if title[0] is not defined %}
    {{ title|trans }}
{% else %}
    {{ title[0]|trans(title[1]) }}
{% endif %}

Ugly, but works.


I found iterable to not be good enough since other objects can also be iterable, and are clearly different than an array.

Therefore adding a new Twig_SimpleTest to check if an item is_array is much more explicit. You can add this to your app configuration / after twig is bootstrapped.

$isArray= new Twig_SimpleTest('array', function ($value) {
    return is_array($value);
});
$twig->addTest($isArray);

Usage becomes very clean:

{% if value is array %}
    <!-- handle array -->
{% else %}
    <!-- handle non-array -->
{% endif % }