We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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



58.4k

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.



31.2k
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