1

For a filemanagement, I use create_function to sort folders(directories) first and then files. But it seems that create_function is deprecated in php 7.2.

So how can I use the usort below correctly?

 $files = array_diff( scandir($dir), array(".", "..", "tmp") );

 usort ($files, create_function ('$a,$b', '
  return    is_dir ($a)
    ? (is_dir ($b) ? strnatcasecmp ($a, $b) : -1)
    : (is_dir ($b) ? 1 : (
        strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) == 0
        ? strnatcasecmp ($a, $b)
        : strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION))
    ))
  ;
'));
mudraya katusha
  • 171
  • 1
  • 8
  • 1
    Use an anonymous function instead of `create_function`. – Barmar May 11 '19 at 09:17
  • https://www.php.net/manual/en/functions.anonymous.php – Barmar May 11 '19 at 09:18
  • @mud you can compare arrays of conditions using the spaceship operator. Here's an example: https://stackoverflow.com/a/56086562/2943403 – mickmackusa May 11 '19 at 10:39
  • 1
    This is working fine: `usort ($files, function ($a,$b) { return is_dir ($a) ? (is_dir ($b) ? strnatcasecmp ($a, $b) : -1) : (is_dir ($b) ? 1 : ( strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) == 0 ? strnatcasecmp ($a, $b) : strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) )) ; });` – mudraya katusha May 11 '19 at 10:54

0 Answers0