Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using in_array on collections

I need to check for a name in an array of names but I having trouble passing an array instead of a collection to the in_array() method.

My blade code looks something like this

@foreach($ecn->areas as $area)
{{ $area->area }}:<br>
<ul>
    @foreach($area->people as $person)                              
        @if(in_array($person, $ecn->signatures->name ))
        <li><del>{{ $person }}</del></li>
        @else
        <li>{{ $person }}</li>
        @endif
    @endforeach
</ul>
@endforeach

I know my problem is in the way im trying to access the list of signatures.

@if(in_array($person, $ecn->signatures->name ))

I can access them in another part of the page doing this

@foreach($ecn->signatures as $signature)
{{ $signature->name }}<br>
@endforeach

and everything is fine.

How can I access and pass the list of signatures as an array in this scenario?

like image 862
CFree Avatar asked Jun 29 '16 16:06

CFree


People also ask

Is In_array case sensitive?

The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

How do you check if an array contains a value in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

If you want to use in_array() version for Laravel Collections then you can use:

$collection->contains($needle)

It woks just like in_array.

If $needle is an integer, an id for example, don't forget to pluck first, like so:

$collection->pluck('id')->contains($needle)
like image 172
Amir Hassan Azimi Avatar answered Oct 18 '22 19:10

Amir Hassan Azimi