I'm trying to determine if a String is included in a array of strings in Laravel.
I have
$rol = 'Admin';
$roles = ['Admin', 'Guest'];
I want to know if $rol is included in $roles without looping.
In Javascript it would be something like this
let array = ['Admin', 'Guest']
let role = 'Admin'
array.includes(role)
If I do this in Laravel, there are some cases I'm not expecting:
Str::contains($rol, $roles) //Output would be true
But if now $roles = ['dmin', 'Guest']
instead of ['Admin', 'Guest']
Str::contains($rol, $roles) //Output would be true but I'm expecting false as 'Admin' is not a $roles element
CodePudding user response:
- use
in_array
function from php. For example:
$rol = 'Admin';
$roles = ["Admin", "Guest"];
if (in_array($rol, $roles)) {
// Matches
}
else {
// Not matches
}
You can also convert the array to the type collection
which is brought to your by Laravel framework. Just simply pass the array to the function collect()
. For example:
$rolesCollection = collect($roles);
After that apply any conditions which are applicable to the collection type.
CodePudding user response:
Laravel has a lot of helper
methods. The one you're likey after is the Arr::has
method:
$role = 'Admin';
$roles = ['Admin', 'Guest'];
$contains = Arr::has($role, $roles);
This method is particularly handy when working with nested arrays. Using dot notation you can perform the same lookup without having to write that logic yourself.
CodePudding user response:
You should not use Str::contains
which checks if the string contains (e.g. has a substring) any of the provided values, but Collection contains, e.g. collect($roles)->contains($rol)
.
CodePudding user response:
Try this one, it's not Laravel but PHP.
$rol = 'Admin';
$roles = ['Admin', 'Guest'];
if (stripos(json_encode($roles),$rol) !== false) {
echo "Found It!";
}