0

I have a PHP array like this:

index.php:

$state = [
  'isLoggedIn' => false,
  'isB2BCustomer' => false
];

print($twig->render('index.html', ['state' => $state]));

index.html:

{% for key, stateItem in state %}
  <tr>
    <td>{{ key }}: {{ stateItem }}</td>
  </tr>
{% endfor %}

This gives me the following output:

|---------------------|
| State               |
|---------------------|
| isLoggedIn:         |
|---------------------|
| isB2BCustomer:      |
|---------------------|

I'm expecting:

|---------------------|
| State               |
|---------------------|
| isLoggedIn: 0       |
|---------------------|
| isB2BCustomer: 0    |
|---------------------|

It shows the keys correctly, but I can't seem to figure out how to get the value.

5
  • Why would you expect 0 for false??? 3v4l.org/DlR10 You'll either need to store 0 or display an actual 0 when the value is false. Commented May 6, 2019 at 20:24
  • @AbraCadaver Twig/PHP outputs booleans as integers right? I'm just doing this as a test to access the values, so I put them in a table to see them. And I expect the false values to be output as 0. Any idea about how to access the values? Commented May 6, 2019 at 20:26
  • 1
    I don't know twig but PHP doesn't output false, maybe {% if stateItem %}1{% else %}0{% endif%} or somesuch. Commented May 6, 2019 at 20:28
  • @AbraCadaver You're right, booleans simply aren't displayed at all like you said. I remember boolean values were automatically type casted to integers (either 0 or 1), but I remember wrong I think. Thanks this solved it. Commented May 6, 2019 at 20:31
  • 1
    "A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values." Commented May 6, 2019 at 20:45

1 Answer 1

1
{% for key, stateItem in state %}
  <tr>
    <td>{{ key }}: {{ stateItem ? '1' : '0' }}</td>
  </tr>
{% endfor %}

Found here: https://twig.symfony.com/doc/2.x/templates.html#other-operators

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.