-1

Possible Duplicate:
Best way to get files from a dir filtered by certain extension in php

What would be the best way to retrieve file names with a specified extension?

I came up with this solution and it works fine but am wondering if there is a better way.

print_r(array_filter(scandir(dirname(__FILE__)), create_function('$a', 'return (substr($a, -4) == ".php") ? true : false ;')));
Community
  • 1
  • 1
Teno
  • 2,582
  • 4
  • 35
  • 57
  • Better in what way? Did you run some Unit Tests? – Wouter Dorgelo Sep 02 '12 at 17:22
  • I'm expecting a better way in readability and efficiency. What does unit test mean? – Teno Sep 02 '12 at 17:24
  • Teno, it's used with Test Driven Development (TDD). By writing tests you, find out of your code is doing it's job. http://www.phpunit.de/manual/3.7/en/automating-tests.html – Wouter Dorgelo Sep 02 '12 at 17:26
  • I see thanks. I don't understand why this question got a down vote as complex857 showed a better solution. It's an important question. – Teno Sep 02 '12 at 17:32
  • Sometimes a question looking like a duplicate can result on conveying another perspective. So what's wrong with it. We get better information then. – Teno Sep 02 '12 at 17:54

1 Answers1

3

I would use glob. Maybe the most simplistic approach to this:

$files = glob( dirname(__FILE__) . '/*.php'); 
$files = array_map('basename', $files);
print_r($files);
complex857
  • 20,425
  • 6
  • 51
  • 54
  • That's better, simple and easy to understand. I was expecting something like this. – Teno Sep 02 '12 at 17:27
  • If the file pattern contains a directory path, the retrieved paths becomes file paths as well. How could it be improved to retrieve only file names? – Teno Sep 02 '12 at 17:48
  • 2
    @Teno `array_map('basename', $files)` – salathe Sep 02 '12 at 17:51
  • One problem with it that we cannot pass a parameter to the function, basename. Otherwise, all fine. – Teno Sep 02 '12 at 18:12