Dave's Brain

Browse - Programming Tips - How do I convert a filesystem directory (folder) to a PHP array?

Date: 2008may6
Updated: 2016nov26
Langauge: PHP

Q.  How do I convert a filesystem directory (folder) to a PHP array?

A.

In php5:

function dir_to_array($dir) { return array_diff(scandir($dir), array('..', '.')); }
Before php5:
function dir_to_array($dir) { $a = array(); if (!($dh = opendir($dir))) return null; while (false !== ($node = readdir($dh))) { if ($node == '.' || $node == '..') continue; $a[] = $node; } closedir($dh); sort($a); return $a; }
Use like this:
function main() { $dir = "/tmp"; $adir = dir_to_array($dir); foreach ($adir as $node) { print "- $node\n"; } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.