Reputation: 363
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 %}
Upvotes: 2
Views: 497
Reputation: 15662
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
}
Upvotes: 2