1

Lets come straight to my problem, these are my folders:

Smarty-3.1.13
Smarty-3.1.15
Smarty-3.1.16
Smarty-3.1.19

this is how i get the foldernames

$smarty_versions = glob("php/Smarty-*");

results:

Array
(
    [0] => php/Smarty-3.1.13
    [1] => php/Smarty-3.1.15
    [2] => php/Smarty-3.1.16
    [3] => php/Smarty-3.1.19
)

now im looking for... em... may a regexp for glob to only select the latest folder.

actually everything what i have inserted as the first parameter into golb what looks like regexp failed :) is there a way so get the last folder like this?

or have i do it like...

$smarty_versions = glob("php/Smarty-*");
$latest_smarty_version = $smarty_versions[count($smarty_versions)-1]; 
//works but i like it more tiny if possible :)

maybe you guys know a other one line solution :D

Dwza
  • 6,494
  • 6
  • 41
  • 73

1 Answers1

3

To use a proper version string comparison, you should use version_compare:

$latest = array_reduce($smarty_versions, function ($latest, $folder) {
    if (!$latest) {
        return $folder;
    }
    $latestNum = preg_replace('!^php/Smarty-!', '', $latest);
    $folderNum = preg_replace('!^php/Smarty-!', '', $folder);

    return version_compare($latestNum, $folderNum, '>') ? $latest : $folder;
});

Assuming of course that Smarty versions follow a compatible convention to what that function expects.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Nice, never seen or used that function before +1 – Lawrence Cherone Jul 11 '14 at 15:36
  • looks nice but... its not a one line code :D don't want to create a extra function. – Dwza Jul 11 '14 at 15:47
  • @Dwza "Create extra function"...?! This is as close as you'll get to "one line of code". Some problems simply are not properly solvable with one line of code. – deceze Jul 11 '14 at 15:49
  • actually this `max(glob("php/Smarty-*"))` is what i was looking for but the guy who posted it to my comment deleted it and didn't open up a post ^^ (and it's a short one line code) – Dwza Jul 11 '14 at 15:50
  • @Dwza that was me, its all going downhill ;p – Lawrence Cherone Jul 11 '14 at 15:52
  • @Dwza Such a simplistic comparison doesn't work correctly anyway! See http://3v4l.org/JC2KN. There's a reason a specialised `version_compare` function exists. – deceze Jul 11 '14 at 15:53
  • @deceze is it possible to pass more variables into the array reduce part ? so i can create a `getLatestVerion("Smarty")` – Dwza Jul 12 '14 at 15:35
  • @Dwza I think you're looking for the `use` syntax of anonymous functions: http://php.net/manual/en/functions.anonymous.php – deceze Jul 12 '14 at 19:11