You can use replace or slice
Jan 12, 2021
29
Level 39
collections 'remove' method ?
I wonder if anyone known how to 'remove' a collection from another with standard methods (I should be able to do it with foreach so it's answer I'm looking for)
$col1=collect(['a','a','2','3','3','4']);
$col2=collect(['a','2']);
expected result : ['a','3','3','4']
Level 75
@sr57 Working code is this
$col1 = collect(['a','a','2','3','3','4']);
$col2 = collect(['a', '2']);
$copy = clone $col2;
$result = $col1->map(function ($item) use ($copy) {
if (in_array($item, $copy->toArray())) {
$key = $copy->search(function ($value) use ($item) {
return $value == $item;
});
$copy->pull($key);
return;
}
return $item;
})->filter()->values()->toArray();
// result -> ['a', '3', '3', '4']
Or (it's almost same)
$col1 = collect(['a','a','2','3','3','4']);
$col2 = collect(['a', '2']);
$copy = clone $col2;
$result = $col1->map(function ($item) use ($copy) {
if ($copy->contains($item)) {
$key = $copy->search(function ($value) use ($item) {
return $value == $item;
});
$copy->forget($key);
return;
}
return $item;
})->filter()->values()->toArray();
// result -> ['a', '3', '3', '4']
Please or to participate in this conversation.