Warm tip: This article is reproduced from serverfault.com, please click

how to check if array contains multi strings Laravel

发布于 2020-12-30 11:55:15

i have collection

Illuminate\Support\Collection {#1453
  #items: array:4 [
    0 => "three"
    1 => "nine"
    2 => "one"
    3 => "two"
  ]
}

and this string

'one', 'two', 'three'

i am trying to validate if these all strings available in array

$array->contains('one', 'two', 'three')

it should return true

but everytime i am getting false

what i am doing wrong please explain thank you

Questioner
sid heart
Viewed
0
Dan 2020-12-30 20:22:13

I use Collection:diff in combination with Collection::isEmpty for a reusable containsAll macro. When the supplied values contain an element that's not included in the collection to check against the result of diff won't be empty and therefore return false.

use Illuminate\Support\Collection;

Collection::macro('containsAll', function (...$values) {
    return collect($values)->diff($this)->isEmpty();
});

$collection = collect(['three', 'nine', 'one', 'two']);
$collection->containsAll('one', 'two', 'three'); // true
$collection->containsAll('one', 'five', 'three'); // false