When grouping array data in PHP, it is often most efficient to generate temporary keys based on the grouping criteria.
I'll use some version terminology based on the accepted answer from: What every digit means in software version (1.7.1.0, for example)?
In this case, the first two integers (Major & Minor release) are used (and they must remain separated by a delimiting character to avoid data collisions). As you iterate, check if the temporary key exists in the output collection. If not, add it. If so, check if the third integer (Maintenance release) is greater than the stored Maintenance release for that Major-Minor release group -- if so, replace the stored Major-Minor release group's value.
This is very concisely performed in my snippet below. If you need the output to be indexed, call array_values()
, otherwise omit that step.
Code: (Demo)
$versions = [
"3.0.1", "3.0.3", "3.0.2", "3.0.0",
"2.9.4", "2.9.3", "2.9.2", "2.9.5", "2.9.1", "2.9.0",
"2.8.1", "2.8.11", "2.8.10"
];
foreach ($versions as $version) {
$ints = explode('.', $version, 3);
$tempKey = "{$ints[0]}.{$ints[1]}";
if (!isset($result[$tempKey]) || version_compare($version, $result[$tempKey], 'gt')) {
$result[$tempKey] = $version;
}
}
var_export(array_values($result));
Output:
array (
0 => '3.0.3',
1 => '2.9.5',
2 => '2.8.11',
)
Using version_compare()
is an appropriate tool to compare versions, but it can be avoided if you wish to make a simple integer to integer comparison on the Maintenance release value. This will cost a little more memory because you will also need to store an array of grouped Maintenance release integers to make this comparison. I am recommending just comparing the full version strings instead.