3

Question heading already asks it:

In a Twig template {{0 in ['a', 'b', '99']}} prints 1. WHY? I have '0' as a value and I can't check it against arrays, as that value always pops up as existing. And at the end of the day: How do I achieve the goal of checking zero against the array of strings, in Twig?

Gelmir
  • 1,829
  • 1
  • 18
  • 28
  • 1
    See: http://stackoverflow.com/q/28437510/3933332 – Rizier123 Jun 21 '16 at 14:38
  • @Rizier123 thanks, but that Q&A doesn't provide me with a solution on how to achieve my goal in Twig. I got the reasons for this, but also need a solution. – Gelmir Jun 21 '16 at 14:57

1 Answers1

1

PHP's type coercion for comparisons goes to integers when necessary. You're checking if an integer is in the array. (int) 'a' is coerced to 0 for this comparison. So 0 is seen as being in the array.

To avoid this, you can use in_array with the strict option:

in_array('0', ['a', 'b', '99'], true)
Matt S
  • 14,976
  • 6
  • 57
  • 76
  • With this in mind, I believe ```var_dump(in_array(0, ['1','2']))``` should yield ```true```, correct? It yields ```false``` though (in PHP 7 at least). Same goes for ```var_dump(in_array(0, [1,2]))``` So why? – Gelmir Jun 21 '16 at 14:44
  • 1
    Because the string `'1'` is coerced to `1`. Character strings are coerced to `0` when compared with any integer. – Matt S Jun 21 '16 at 14:46
  • Ok, so how do we compare against integer zero then, in Twig of course? – Gelmir Jun 21 '16 at 14:49
  • For an array of integers (or integer string), use `in`. For an array with a mix of integers and character strings, my answer is above: `in_array` with the strict option. – Matt S Jun 21 '16 at 15:02
  • Twig has ```in_array``` function? – Gelmir Jun 21 '16 at 15:06
  • Not directly, you'll have to create an extension or use an existing one. – Matt S Jun 21 '16 at 15:11