Marcello Pato
Marcello Pato

Reputation: 484

Diff values between arrays

I have these two arrays as a result of requests:

$f = DocsPf::where('renda', '=', 2)->where('tipo', '=', 'R')->pluck('id');
$f = [4,5,6,7,8,9,10]

And

$d = Documento::where('user_id', '=', $id)->pluck('cad_doc_id');
[4,5,6,7,8]

Now I want to make a request to a model only with the difference between those arrays, like:

$missing = Docs::where('id', '=', 9)->first();

and

$missing = Docs::where('id', '=', 10)->first();

I´ve did

$ids = array_diff($f, $d);
        return $ids;

...as the brother bellow wrote, but got hits error:

array_diff(): Expected parameter 1 to be an array, object given

Any helps, please?

Upvotes: 0

Views: 140

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

You can use array_diff() on the two arrays to get unique values:

$array1 = [4,5,6,7,8,9,10];
$array2 = [4,5,6,7,8];

$uniqueIds = array_diff($array1, $array2); // `[9, 10]`

$missing = Docs::whereIn("id", $uniqueIds)->get();
// Will return a `Collection` of `Doc` models based on the passed `ids`

-- Edit --

If $array1 and $array2 are Collections, you can use the diff() function:

$array1 = collect([4,5,6,7,8,9,10]);
$array2 = collect([4,5,6,7,8]);

$uniqueIds = $array1->diff($array2);
$missing = Docs::whereIn("id", $uniqueIds)->get();
// Note: You may need to do `$uniqueIds->toArray()` if it complains further.

One more alternative, you can convert $array1 and $array2 to arrays before using array_diff()

$uniqueIds = array_diff($array1->toArray(), $array2->toArray());

It's a little redundant, but should help demonstrate the difference between an array and a Collection

Upvotes: 2

Related Questions