Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - array_pop?

Tags:

twig

I have a multi dimensional array along the lines of

array(2) { 
    [11]=> array(1) { 
        ["L2J"]=> array(1) { 
            ["VS7"]=> array(2) { 
                ["26 Feb 2015 12:00"]=> array(2) { 
                    ["C"]=> string(1) "9" 
                    ["D"]=> string(1) "9" 
                } 
                ["26 Feb 2015 13:00"]=> array(2) { 
                    ["C"]=> string(1) "9" 
                    ["D"]=> string(1) "6" 
                } 
            } 
        } 
    } 
}

Now I have done some looping and I am now at the point where I have access to the dates.

{% for sid, psuedos in alerts %}
    {% for psuedo, flights in psuedos %}
        {% for flight, dates in flights %}

        {% endfor %}
    {% endfor %}
{% endfor %}

Now I am converting some normal PHP code and at this point, I would do

$firstDate = array_pop(array_keys($dates));

Is there any way to do something like this in Twig? I have searched about but cant seem to find anything.

Update

This is my latest effort, can't seem to get it to slice the last array element though

{% set firstDate = [dates|keys]|last|slice(1) %}
like image 273
Nick Price Avatar asked Dec 02 '22 17:12

Nick Price


2 Answers

There isn't a Twig function that will do exactly what array_pop() does (return the last array element and shorten the array at the same time), but there are ways to do them separately.

Given:

{% set array = [1,2,3,4,5] %}

To get the last element, use Twig's last filter.

{{ array|last }}

{# returns '5' #}

You can remove only the last element with the slice filter like this: slice(0,-1)

{% set array = array|slice(0,-1) %}

{# array = [1,2,3,4] #}

... or the Craft without filter:

{% set arrayLast = array|last %}

{% set array = array|without(arrayLast) %}

{# array = [1,2,3,4] #}
like image 104
Alex Roper Avatar answered Dec 24 '22 09:12

Alex Roper


pop last element

{% set array = [1,2,3] %}

{% set value = array|last %}

{{ value }}  {# return 3 #}

{% set array = array|slice(start, length - 1) %}

{% for value in array %}

{{ value }}  {# return 1,2 #}

{% endfor %}

pop the first element

{% set array = [1,2,3] %}

{% set value = array|first %}

{{ value }} {# return 1 #}

{% set array = array|slice(start + 1, length) %}

{% for value in array %}

{{ value }} {# return 2,3 #}

{% endfor %}
like image 45
Nick miller Avatar answered Dec 24 '22 09:12

Nick miller