cgm225 Posted February 8, 2008 Share Posted February 8, 2008 I have a piece of code (see below) that creates an array of a directory's subdirectories, without the inclusion of files names, and is not recursive. However, now I want to turn it into a function ( something like function subdirectory_array ($directory) ) so that I can set variables to equal the resulting array. So instead of having this: $test = array('subdirectory1','subdirectory2','subdirectory3'); I can have this: $test = subdirectory_array ("some/directory/here"); I want to know what the best way to code my function would be based on the code I have already created below. Thank you all in advance! <?php //This code creates array of a directory's subdirectories, without the inclusion of files names, and is not recursive $directory = "/example/directory/here"; $dh = opendir($directory); $dh_array = array(); while (($file = readdir($dh)) !== false) { if($file != "." && $file != "..") { if ((substr($file, -4, -3) == ".") OR (substr($file, 0, 1) == ".")){ } else { array_push($dh_array, $file);} } } print_r($dh_array); ?> Quote Link to comment https://forums.phpfreaks.com/topic/90103-solved-turning-piece-of-code-into-function-goal-is-to-output-array-best-practice/ Share on other sites More sharing options...
schilly Posted February 8, 2008 Share Posted February 8, 2008 put it in a separate file, include the file in the page you want to use it in then just call: $array = subdirectory_array($dir); where $dir would be your original directory variable. <?php //This code creates array of a directory's subdirectories, without the inclusion of files names, and is not recursive function subdirectory_arrary($directory){ $dh = opendir($directory); $dh_array = array(); while (($file = readdir($dh)) !== false) { if($file != "." && $file != "..") { if ((substr($file, -4, -3) == ".") OR (substr($file, 0, 1) == ".")){ } else { array_push($dh_array, $file);} } } return $dh_array; } ?> Hope that helps. Quote Link to comment https://forums.phpfreaks.com/topic/90103-solved-turning-piece-of-code-into-function-goal-is-to-output-array-best-practice/#findComment-462000 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.