Support the ongoing development of Laravel.io →
posted 10 years ago
Blade
Last updated 1 year ago.
0
Solution

Have you tried

foreach($array as $key => $value) {
if($key == 0)
...
}
Last updated 1 year ago.
0

2u3 said:

Have you tried

foreach($array as $key => $value) {
if($key == 0)
...
}

How stupid of me, thanks!

Last updated 1 year ago.
0

What about reset($array)

Last updated 1 year ago.
0

Rather than use a foreach loop you could just directly access the first item in the object:-

{{ $blog->entries{0}->title }}
Last updated 1 year ago.
0

can somebody add how to get the last element? I'm sure one can use a counter , but I don't know how ...

0
if ($key == count($array))
Last updated 8 years ago.
0

@port22 - if you area trying to get last element of an ARRAY, you can use Laravel's helper function:

$lastElement = last($array);

$firstElement = head($array);
Last updated 8 years ago.
0

2u3 said:

Have you tried

foreach($array as $key => $value) {
if($key == 0)
...
}

perpahs this is a solution but sometimes you don't have keys starting at 0

i found this: http://robin.radic.nl/blade-extensions/directives/foreach.html

@foreach($array as $key => $value)
@if ($loop->first)
...
@endif
@endforeach
Last updated 8 years ago.
0
@foreach($sidebar_menus as $sm)
@if($sidebar_menus->first() == $sm)
...
@endif
@endforeach
Last updated 8 years ago.
0

I know it's solved. but another option to get the first element is with first(). if it's an array wrap it in a collection otherwise collections already have it.

collect(\Blog::GetEntries(1, 5, true)->entries)->first();

although an eloquent model already returns a collection so the collect part likely isn't needed.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

lorienhd lorienhd Joined 20 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.