3

I'm using glob to array my sub directories

<?php
$items = glob("../albums/*", GLOB_ONLYDIR);
foreach($items as $item) {
    echo "$item\n ";
}
?>

he orders them by the alphabet, i'd like to order them by numbers

if i got sub-directories named 1 , 3 , 5 , 10

the will be arranged like this : 10, 1, 3, 5

i want them to be like this 1, 3, 5, 10

is there an option? thanks

EDIT: now i found natsort($files); and when im using it with:

$items = array_slice(glob('albums/*', GLOB_ONLYDIR), 0, 4);
natsort($items);

and my folders are 995-1000 it gives me this array : 995, 996, 997, 1000

Elad
  • 75
  • 2
  • 10

4 Answers4

8

Take a look at natsort()

Niko
  • 26,516
  • 9
  • 93
  • 110
  • but now its making a conflict, when used in `$items = array_slice(glob('albums/*', GLOB_ONLYDIR), 0, 4); natsort($items); ` and the folders are 995,996,997,998,999,1000 it gives the 995,996,997 and 1000 – Elad Sep 15 '11 at 09:13
  • 1
    you need to do the sorting before the slicing: `$items = glob(..); natsort($items); $items = array_slice($items, 0, 4);` – Niko Sep 15 '11 at 09:23
5

use natsort to sort the array in natural order:

natsort($array);
Headshota
  • 21,021
  • 11
  • 61
  • 82
1

You could sort the array after the glob:

sort($items, SORT_NUMERIC);
Alexander Sulfrian
  • 3,533
  • 1
  • 16
  • 9
1

You can achieve this by using array sorting natsort() like this;

$items = glob("../albums/*", GLOB_ONLYDIR);
natsort($items);

Now if print this array then you get the proper result by this.

print_r($items);
Kerem
  • 11,377
  • 5
  • 59
  • 58
pravat231
  • 782
  • 1
  • 11
  • 26