Home » Php » php – Twig returns true even if not in array (checked field)

php – Twig returns true even if not in array (checked field)

Posted by: admin February 25, 2020 Leave a comment


I am probably doing it wrong but I am running through an array of values like this.

    {% for checkboxDataKey, checkboxData in checkbox %}
     <div class="form-check">
                <input class="form-check-input checkbox-questionlist" type="checkbox"
            {% if checkboxDataKey in values %} checked {% endif %}
            data-report-id="{{ reportId }}" name="{{ name }}" value="{{ checkboxDataKey }}" id="{{(name)}}-{{checkboxDataKey}}">
        <label class="form-check-label" for="{{(name)}}-{{checkboxDataKey}}">
            {{ checkboxData.answer }}
    {% endfor %}

It is checking if the checkboxDataKey is in the value array. This is working until I add the different value to the array (it is named different).

 array(2) { [0]=> string(1) "3" [1]=> string(9) "different" } 

When this is selected the first checkbox is also checked and I cannot find out why, since the value 0 is not in the array.

enter image description here

When I look at the checkbox row keys
array(5) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) [4]=> int(4) } they are integers.

How to&Answers:

It was indeed an PHP problem. When I ran an in_array function it returned an true. So I had to do this, to tackle it.

 foreach ($fields['answers'] as $key => $value) {
            $options[$key] = array_merge($value, ['checked' => in_array((string)$key, $values)]);


You are comparing a string array with an integer array, which may lead to strange results.