Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.