PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] how to check if array contains multi strings Laravel

 November 15, 2022     laravel, laravel-5, laravel-6, laravel-7, laravel-8     No comments   

Issue

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


Solution

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


Answered By - Dan
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing