Search code examples
arraysxmltwigsimplexml

Twig "in" operator with SimpleXMLElement and keys array


Here I have an issue matching an SimpleXMLElement attribute "name" matching keys in an array. When I dump the result of the attribute matching the string key by calling the array's key, the result is true as expected. But when I try to let it match by using the in operator, the result is false.

Twig:

{{ dump(options|keys) }}
{% for tense in verbXML %}
{{ dump(tense.attributes.name) }}
{{ dump(tense.attributes.name == (options|keys)[1]) }}
{{ dump(tense.attributes.name in options|keys) }}
{% endfor %}

Result:

   array:2 [▼
      0 => "neg-imperative"
      1 => "present"
    ]

    SimpleXMLElement {#835 ▼
      +"0": "present"
    }

    true

    false

Solution

  • As Alain Tiemblo suggested, using (tense.attributes.name ~ '') in options|keys was the answer. Thank you!