1

I've asked to do a loop into an array who looks like this:

Array
(
    [0] => 215950741
    [1] => 3900
    [2] => 10527160
    [3] => 2873
...
    [44] => N~~~~
    [45] => N~~~~
    [46] => historico_estados
    [47] => 18/10/2018 16:03:09~10~Solicitada~ARANJUEZ~0~2873~   ~
    [48] => 18/10/2018 16:06:42~13~Aceptada~ARANJUEZ~0~2873~   ~
    [49] => 18/10/2018 18:15:49~3~Tránsito~SANTANDER~0~3900~   ~
    [50] => 18/10/2018 22:28:49~3~Tránsito~PLATVITORIA~0~9001~   ~
    [51] => 19/10/2018 04:19:33~3~Tránsito~PLATMADRID~0~9028~   ~
    [52] => 19/10/2018 08:15:53~2~Reparto~ARANJUEZ~0~2873~   ~
    [53] => 19/10/2018 09:37:00~1~Entregado~RECEPTOR~0~2873~   ~
)

I need to loop from the entry 46 of the array to the end, I've tried to do something but isn't working at all, and the plus of this I had to do it solely in Twig, so I am kinda lost. I can get the last entry of the array using the lastfunction of twig.. but can't find something to get the last entries.

2

2 Answers 2

4

In twig, you could accomplish this with a for loop:

{% for i in 44..array|length-1 %}
    {{ array[i] }}
{% endfor %}

See an example output here.

Additionally (Thanks to splash58's comment), you can access via the slice operator. From the docs:

{% for i in [1, 2, 3, 4, 5][start:length] %}
    {# ... #}
{% endfor %}

{{ '12345'[1:2] }} {# will display "23" #}

{# you can omit the first argument -- which is the same as 0 #}
{{ '12345'[:2] }} {# will display "12" #}

{# you can omit the last argument -- which will select everything till the end #}
{{ '12345'[2:] }} {# will display "345" #}

So you can accomplish this, like below:

{% for item in array[44:] %}
   {{ item }}
{% endfor %}

See an example output of this here.

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

4 Comments

I guess OP needs it in twig, not PHP.
That's the point, I can do it on php but I don't know how to reproduce it in Twig. I've take a look into the docs of twig but.. twig.symfony.com/doc/2.x/tags/for.html
@wiitohzjeh I've updated my post (I do apologize, read it as PHP when I skimmed over it).
Thanks, I've finally got it:
0

You can use loop variable inside for

{% for el in elems %}
    {% if loop.index0 > 45 %}
        {# do some stuff #}
    {% endif %}
{% endfor %}

https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable

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.