Home » Php » php – Using in_array on collections

php – Using in_array on collections

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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)

Answer:

You can use the lists or pluck method on the signatures collection to get a new collection of all the names. From there, you can either use the contains() method on the collection, or you can use the all() method to turn the collection into an array and use in_array directly.

I would suggest doing this outside of the foreach loop, so you’re not generating this new collection and array every iteration.

Array:

// controller
$names = $ecn->signatures->lists('name')->all();

// blade
@if(in_array($person, $names))

Collection:

// controller
$names = $ecn->signatures->lists('name');

// blade
@if($names->contains($person))

You can also use contains() with a closure, which would let you get away with not creating an intermediate collection, but it’s a little harder to read:

Contains with closure:

// blade
@if($ecn->signatures->contains(function ($key, $value) use ($person) {
    return $value->name == $person;
}))

Answer:

As per Laravel Docs

The get method returns an array of results where each result is an instance of the PHP StdClass object.

So you must convert your stdClass object to a array in your controller itself.

foreach ($ecn->signatures as $signature) 
     $nameArray[] = $signature->name;

and then you can use in_array in the blade template

@if(in_array($person, $nameArray))