1

I have the following passed as an array to my Twig template:

Array
(
    [0] => Array
        (
            [url] => http://somedomain.com/somepage1
            [0] => http://somedomain.com/somepage1
            [count] => 27
            [1] => 27
        )

    [1] => Array
        (
            [url] => http://somedomain.com/somepage2
            [0] => http://somedomain.com/somepage2
            [count] => 7
            [1] => 7
        )

)

Now I need to do something like this:

foreach ( $response as $key => $element ) {
    if ( global.request.uri == $response->url ) {
        break;
    }
}

I know how to imitate break in Twig (from this answer), but I don't know how to imitate as $key => $element. So how do I stop my loop when it finds an object containing the string that meets my condition? Moreover, how do I then output the value of count in that object?

Unlike this question, my arrays contain multiple keys each with some values assigned to each key, and not just "alpha/bravo" strings. So I don't understand how to apply the answer to that question to my case.

COOLak
  • 379
  • 3
  • 15
  • 1
    Possible duplicate of [Twig for loop and array with key](https://stackoverflow.com/questions/10299202/twig-for-loop-and-array-with-key) – DarkBee Feb 27 '19 at 14:20
  • I found that question before posting mine, I didn't understand how to use the answer in my case though. – COOLak Feb 27 '19 at 14:26
  • As you can see, my arrays contain multiple keys each with some values assigned to each key, and not just "alpha/bravo" strings. – COOLak Feb 27 '19 at 14:34

1 Answers1

2

Based on your data and the comments, I'm not even sure you'd need the key to solve your problem

{% for item in items if item.url == uri %}
    {{ item.count }}
{% endfor %}

demo


EDIT

As of twig 2.10.0 it's deprecated to use an if directly inside the for-statement, now you either place the if inside the block or use the filter filter

{% for item in items %}
    {% if item.url == uri %}
        {{ item.count }}
    {% endif %}
{% endfor %}
{% for item in items|filter(v => v.url == uri) %}
    {{ item.count }}
{% endfor %}
DarkBee
  • 16,592
  • 6
  • 46
  • 58