Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahmeda's avatar

How to get the nearest expiration date?

I have this array string :

[
 {"expiration": "0000-00", "quantity": -50},
 {"expiration": "2023-02", "quantity": 100},
 {"expiration": "2022-03", "quantity": 50}
]

how to get the nearest expiration date, means here I need to get the third one 2022-03 and ignore others & also ignore the date that comes with 0000-00

my code:

$minDate = "";

foreach (json_decode($row['items']) as $item) {
    if ($item->expiration != "0000-00") {
        $minDate = min($item->expiration);
    }
}

dd($minDate);

0 likes
8 replies
Sinnbeck's avatar

Something like this

$items = collect(json_decode($row['items']));
$last = $items->filter(fn ($item) => $item->expiration != "0000-00")->sortByDesc('expiration', SORT_NATURAL)->first();
tykus's avatar
tykus
Best Answer
Level 104

You will want to sort the Collection; and then get the first item where the expiration is in the Future:

collect(json_decode($row['items'], true))
   ->sortBy('expiration')
  ->filter(fn ($item) => Carbon\Carbon::createFromFormat('Y-m', $item['expiration'])->isFuture())
  ->first()
bugsysha's avatar

Or if the data is already sorted you just get the last element? The data sample you've provided is very small so it is hard to fully understand what data you will be working with.

ahmeda's avatar

@bugsysha it's something like this

[{"expiration": "0000-00", "quantity": 75}, {"expiration": "2023-02", "quantity": 100}, {"expiration": "2024-02", "quantity": 50}]

[{"expiration": "0000-00", "quantity": 500}, {"expiration": "2025-02", "quantity": -200}]

	[{"expiration": "0000-00", "quantity": -50}, {"expiration": "2023-02", "quantity": 100}]
tykus's avatar

@Jean_ali the solution I shared will solve for any original ordering of objects

1 like
bugsysha's avatar

@Jean_ali if those are 3 different examples, then it looks like you are always getting your data sorted and you don't need to worry about sorting. So just get the last element in the array. Sorting is a very expensive operation so you should avoid it if you can.

ClaudeMjDevinHenry's avatar

$arr = getNearestExp($row['items']); print_r($arr);

/** *To get the Nearest Expiration date *@input json https://echat.date array of expiration & quantity as *per the question */ function getNearestExp($items){ $items = json_decode($items); // convert the items to json object $itemArr = [ https://e-chats.com/omegle ];

foreach($items as $item) {
    // exclude the '0000-00' expiration
    if($item->expiration != '0000-00'){ 
        $itemArr[strtotime($item->expiration)] = (array)$item;
    }
    
}

// sort the out put array to ASC order to get the smallest value 1st
ksort($itemArr);

// Re indexing the array to proper index keys
$itemArr= array_values($itemArr);

// return the first value of the array
return $itemArr[0];

}

Please or to participate in this conversation.