1

Creating a site using Codeigniter. I have used codeigniters directory helper to get the filenames of all files in a directory:

$this->load->helper('directory'); $files = directory_map('directory_name/', 1);

This all works as expected and I get a list of the files in the directory - print_r($files) proves this.

However, the file names all start with numerical values:

 1_firstfile.doc  
  2_nextfile.doc  
  3_another.exe  
  ...   ...  
  11_thisfile.txt  
  12_filename.pdf

My problem is that the files are returned in a different order that I would like. I wish them to be returned in the order above, but instead they are returned like this:

 1_firstfile.doc    
  11_thisfile.txt  
  12_filename.pdf  
  2_nextfile.doc   
  3_another.exe 

Obviously, they are being returned in alphabetical order, but I need them returned in numerical order.

I have tried $files = sort($files,1) but that seems to just empty the array. So, apart from changing the filename, how can I get the array to arrange them in the order I require?

2
  • line 1 = sort($files); line 2 print_r($files); You do not need to assign a sort to a var Commented Dec 23, 2014 at 9:27
  • use natsort() for this Commented Dec 23, 2014 at 9:31

1 Answer 1

3

All sort() functions are "pass by reference", so it actually modifies the argument directly, returning a success or failure status, so

$files = sort($files)

sorts $files, but then assigns the success status (a Boolean true/false) to $files

Simply do

sort($files)

Note that to sort cleanly by the numeric part of the filename, you should be using sort() with the SORT_NATURAL flag, or natsort()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.