简体   繁体   中英

Twig parse array and check by key

I'm trying to see if an array has a key. The first case returns 2 results 1-5 and, while the second seems to work fine.

Any ideea why is this happening?

{% set options = {'1' : '1' , '1-5' : '5' , '1-12' : '12' } %}
{% set selected = '1-5' %}

Wrong check
{% for k,v in options %}
    {% if k == selected %}    
        {{ k }}
    {% endif %}    
{% endfor %}


Right
{% for k,v in options %}    
    {% if k|format == selected|format %}    
        {{ k }}
    {% endif %}        
{% endfor %}

https://twigfiddle.com/c6m0h4

Twig will compile the "wrong check" in the following PHP snippet:

if (($context["k"] == (isset($context["selected"]) || array_key_exists("selected", $context) ? $context["selected"] : (function () { throw new RuntimeError('Variable "selected" does not exist.', 6, $this->source); })()))) {

Simplified this becomes

if ($context["k"] == $context["selected"])

Because the type of context["k"] (for the first iteration) is an integer, PHP will typecast the right hand part of the equation to an integer as well. So the equation actually becomes the following:

if ((int)1 == (int)'1-5') 

and casting 1-5 to an integer becomes 1 , making the final equation to:

1 == 1 which evaluates to true


You can test the fact that first key gets treated as integer with the following PHP snippet by the way

<?php

$foo = [ '1' => 'bar', ];
$bar = '1-5';

foreach($foo as $key => $value) {
    var_dump($key); ## output: (int) 1
    var_dump($key == $bar); ## output: true
}

demo

Because of the absence of strict comparison, to achieve that you can use is same as

{% for k,v in options %}
    Wrong true
    {% if k is same as(selected) %}    
        {{ k }}
    {% endif %}    

Note:- same as checks if a variable is the same as another variable. This is the equivalent to === in PHP:

It's not the fault of twig, but of PHP. The first index k gets treated as an integer (int)1 so in the equation PHP will typecast the string to an int: (int)1 == (int)'1-5' which validates to true

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM