increase Posted December 13, 2023 Share Posted December 13, 2023 I have a text file in the following format 03/12/2023 06 This is the text in the line 03/12/2023 06 This is the text in the line 03/12/2023 06 This is the text in the line 03/12/2023 06 This is the text in the line 22/11/2023 06 This is the text in the next line 22/11/2023 06 This is the text in the next line 03/11/2023 06 This is another text in the line 03/11/2023 06 This is another text in the line 03/11/2023 06 This is another text in the line 04/12/2023 06 This is yet another text in the line 04/12/2023 06 This is yet another text in the line Which is read into an array $data, from this array, I want to output the earliest date which in this case would be 03/11/2023 Quote Link to comment Share on other sites More sharing options...
requinix Posted December 13, 2023 Share Posted December 13, 2023 What code have you tried so far and what happened when you ran it? Quote Link to comment Share on other sites More sharing options...
Barand Posted December 13, 2023 Share Posted December 13, 2023 use usort() with a callback function which converts the first 10 chars of each line to yyyy-mm-dd format and compares them. Quote Link to comment Share on other sites More sharing options...
Psycho Posted December 13, 2023 Share Posted December 13, 2023 $earliestDateTs = false; foreach($data as $line) { $dateStr = substr($line, 0, 10); //Get just the date part of the string $dateTs = strtotime($dateStr); //Convert the date string to a timestamp if(!$earliestDateTs) { $earliestDateTs = $dateTs; } //If earliestDateTs not set (i.e. first iteration) set to this line's timestamp $earliestDateTs = min($dateTs, $earliestDateTs); //Set earliestDateTs to the minimum of the current value or this line's timestamp } echo "Earliest date: " . date('m/d/Y', $earliestDateTs); Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted December 14, 2023 Solution Share Posted December 14, 2023 Alternatively usort($data, fn($a, $b) => isoDate($a) <=> isoDate($b)); echo $data[0]; //--> 03/11/2023 06 This is another text in the line function isoDate($text) { $d = substr($text, 0, 10); return DateTime::createFromFormat('d/m/Y', $d)->format('Y-m-d'); } 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.