3

Can someone tell me how to iterate over array keys without knowing their values ? For example:

array:3 [▼
  "name" => "AccountId"
  "activated" => "false"
  "type" => "string"
]

I'd like to get a select list with:

<select name="select">
  <option>name: AccountId</option>
  <option>activated: false</option>
  <option>type: string</option>
</select>

2 Answers 2

5

You can Iterating over Keys and Values as described in the doc, as example:

<select name="select">
    {% for key, value in users %}
       < option > {{ key }}: {{ value }}</option >
    {% endfor %}
</select>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer ! can you please tell me about this error ? Key "key" doesn't exist ? why it doesn't take the value of key instead of "key" <select name="select"> {% for key,value in array %} {% if (key != 'id') and (key != 'type') %} <option value={{key}}>{{ array.key }}</option> {% endif %} {% endfor %} </select>
uhmm seems due to the {{ array.key }} try with {{ value }} as described in the provided answer
Well actually your answer helped me to write the for loop but in my page 'value' is an array so I thought that I could access to its attributes by the doing value.key but it doesn't work when it dynamically ( if i do value.type it works )
3

Something like this should do the trick:

<select>
    {% for key, value in data %}
        <option>{{ key }}: {{ value }}</option>
    {% endfor %}
</select>

You can read more about for loop in Twig's documentation.

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.