0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel collectionクラスのvalueで比較する(完全一致)

Last updated at Posted at 2023-06-12

前提

二つのコレクションクラスのvalueを比較し完全一致するかを確認する

実装

.php
$Acollection = collect([1,2,3]);
$Bcollection = collect([1,2,3]);

//ソートで順番を合わせ、ユニークにする。
//valuesメソッドはキーをリセット後、連続した整数にした新しいコレクションを返します。

$Acollection = $Acollection->unique()->sort()->values();
$Bcollection = $Bcollection->unique()->sort()->values();

if ($Acollection == $Bcollection)
{
  //一致
}
else
{
  //不一致
}

実装例1(同じvalueで順番が異なる)

.php
$Acollection = collect([1,2,3]);
$Bcollection = collect([3,2,1]);

$Acollection = $Acollection->unique()->sort()->values();
$Bcollection = $Bcollection->unique()->sort()->values();

//$Acollectionと$Bcollection 
Illuminate\Support\Collection {#2483 ▼
  #items: array:3 [▼
    0 => 1
    1 => 2
    2 => 3
  ]

実装例2(重複がある)

.php
$Acollection = collect([1,2,3,3,2]);
$Bcollection = collect([3,2,1]);

$Acollection = $Acollection->unique()->sort()->values();
$Bcollection = $Bcollection->unique()->sort()->values();

//$Acollectionと$Bcollection 
Illuminate\Support\Collection {#2483 ▼
  #items: array:3 [▼
    0 => 1
    1 => 2
    2 => 3
  ]

実装例3(異なる値)

.php
$Acollection = collect([1,2,3,4]);
$Bcollection = collect([3,2,1]);

$Acollection = $Acollection->unique()->sort()->values();
$Bcollection = $Bcollection->unique()->sort()->values();

//$Acollection
Illuminate\Support\Collection {#2483 ▼
  #items: array:4 [▼
    0 => 1
    1 => 2
    2 => 3
    3 => 4
  ]

//$Bcollection 
Illuminate\Support\Collection {#2551 ▼
  #items: array:3 [▼
    0 => 1
    1 => 2
    2 => 3
  ]

//上記はfalseになる
if ($Acollection == $Bcollection)
{
  //一致
   dump(true)
}
else
{
  //不一致
  dump(false)
}

//false

参照

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?