Jump to content

[SOLVED] Turning piece of code into function, goal is to output array, best practice..


cgm225

Recommended Posts

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);

?>

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.