Search code examples
phparrayslaravelcollections

Check if first two items in Laravel collection have same date; if not, select the item with the greater date


I have a collection that contain two arrays :

array:2 [
  0 => array:3 [
 
    "cde" => "cd542"
    "startDate" => "2022-10-27"
    "endDate" => null
  ]
  1 => array:3 [
    "cde" => "cd547"
    "startDate" => "2022-10-27"
    "endDate" => null
  ]
]
  1. take the first element if they have the same code & the same start date
  2. if they have different startDate take the most recent one

i tried the ->contains method but is not working


Solution

  • This feels like an odd use case but this should get you on the right track:

    $sameElements = [
        [
            "Code" => "AKAR02",
            "startDate" => "2022-10-27",
            "endDate" => null,
        ],
        [
            "Code" => "AKAR02",
            "startDate" => "2022-10-27",
            "endDate" => null,
        ]
    ];
    
    $collection = collect($sameElements);
    [$first, $second] = $collection->only(0, 1);
    
    if (
        $first['code'] === $second['code']
        && $first['startDate'] === $second['endDate']
    ) {
        // take the first element if they have the same code & the same start date
    } else {
        // do something else?
    }
    
    //if they have different startDate take the most recent one
    $diffElements = [
        [
            "Code" => "AKAR02",
            "startDate" => "2022-10-27",
            "endDate" => null,
        ],
        [
            "Code" => "AKAR02",
            "startDate" => "2022-10-01",
            "endDate" => null,
        ]
    ];
    
    $collection = collect($diffElements);
    [$first, $second] = $collection->only(0, 1);
    
    // if they have different startDate take the most recent one
    if ($first['startDate'] != $second['startDate']) {
        // do something with the most recent one
        $mostRecent = $collection->sort(function ($a, $b) {
            return strtotime($a['startDate']) <=> strtotime($b['startDate']);
        })->first();
    } else {
        // do something else
    }