Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Access first item of array in volt

How do I access first item of an array in volt?

I have an array assign to Volt, it's an arrary contains objects, I know loop could do the job, but I wonder if I could access to first from array directly. I have tried with

{{ arrayList[0].id }}

and

{{ arrayList.0.id }}

both of them are not working



36.3k

Hi

Could you diedup array in Volt

{{ dump(arrayList)}}


92
edited May '15

Using {{ arrayList[0].id }} will produce ($arrayList[0])->id in the php code generated in volt - causing the error you saw.

This can be overcome by setting the first item in the array to a variable and then accessing it:

{% set firstItem = arrayList[0] %}
{{ firstItem->id }}

Not as elegant as you were trying, but gets around how volt is parsed.



15.1k
Accepted
answer

Arrays:

  {{ arrayList[0]['id'] }} // translates to arrayList[0]['id']

objects

  {{ arrayList.[0].id }} // translates to $arrayList[0]->id

try using the dump feature as suggested to see the output.



92
edited May '15

Your arrays answer works for me, however it is not any use for an array of objects.

Your object solution does not, resulting in an error.

{{ arrayList.[0].id }} // translates to $arrayList->array(0)->id