Get latest from array of microtimes



I am looping through a list of files and grabbing their modified date, which is returned in microtime format:

int(1633986072)
int(1633971686)
int(1634014866)
int(1634000474)

I can loop through these, but unsure which function is best to identify which is the latest.

Is strtotime best method here or maybe any other alternatives?

Answer

Functions like filemtime return the time as a Unix timestamp. The time stamps can be collected in an array.

$timeStamps = [
  1633986072,
  1633971686,
  1634014866,
  1634000474
];

You get the last value with the max function.

$lastTs = max($timeStamps);  //1634014866

With the date function, you can display the timestamp as human-readable local time. Example for time zone Europe/Berlin:

echo date('Y-m-d H:i:s',$lastTs);  //2021-10-12 07:01:06

Edit: To the additional question how can I return the two highest values?

For this, rsort is used to sort the timestamps in descending order. The highest value, the second highest, etc. can then easily be accessed via index as long as there are values in the array.

rsort($timeStamps);
$lastTs = $timeStamps[0];  //1634014866
$last2Ts = $timeStamps[1]; //1634000474


Source: stackoverflow