Black
Black

Reputation: 20232

Laravel Blade - check if data array has specific key

I need to check if the data array has a specific key, I tried it like this:

@if ( ! empty($data['currentOffset']) )
    <p>Current Offset: {{ $currentOffset }} </p>
@else
    <p>The key `currentOffset` is not in the data array</p>
@endif

But I always get <p>The keycurrentOffsetis not in the data array</p>.

Upvotes: 11

Views: 26655

Answers (4)

DEV Tiago Fran&#231;a
DEV Tiago Fran&#231;a

Reputation: 1696

ternary

 @php ($currentOffset = isset($data['currentOffset']) ? $data['currentOffset'] : '')

Upvotes: 0

YouneL
YouneL

Reputation: 8351

I think you need something like this:

 @if ( isset($data[$currentOffset]) )
 ...

Upvotes: 5

Sahil Purav
Sahil Purav

Reputation: 1354

Use following:

@if (array_key_exists('currentOffset', $data))
    <p>Current Offset: {{ $data['currentOffset'] }} </p>
@else
    <p>The key `currentOffset` is not in the data array</p>
@endif

Upvotes: 4

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can use @isset:

@isset($data['currentOffset'])
    {{-- currentOffset exists --}}
@endisset

Upvotes: 28

Related Questions