Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to put this PHP into an array and simplify it?

Tags:

php

wordpress

The following code loads all .php files found in the specified folder (defined separately). Is there a way to put this into an array to simplify the code?

Only a couple of variables change but essentially the code repeats several times.

// The General Files

$the_general = opendir(FRAMEWORK_GENERAL);

while (($the_general_files = readdir($the_general)) !== false) {
    if(strpos($the_general_files,'.php')) {
        include_once(FRAMEWORK_GENERAL . $the_general_files);       
    }       
}

closedir($the_general);


// The Plugin Files

$the_plugins = opendir(FRAMEWORK_PLUGINS);

while (($the_plugins_files = readdir($the_plugins)) !== false) {
    if(strpos($the_plugins_files,'.php')) {
        include_once(FRAMEWORK_PLUGINS . $the_plugins_files);       
    }       
}

closedir($the_plugins);

There are several more sections which call different folders.

Any help is greatly appreciated.

Cheers, James

like image 851
James Morrison Avatar asked Jul 18 '10 13:07

James Morrison


People also ask

How do you simplify an array in PHP?

To accomplish this you can simply use array union operator.

Is PHP an array?

The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.

How to insert string into array in PHP?

In more modern days you could add strings or other data types to an array with Square Bracket method like this: $arr = ['hello']; $arr[] = 'world'; This approach will add the string 'world' to the $arr array variable. array_push would be more suitable if you were to push more than one element into the array.


2 Answers

I nicer way to do this would to use glob(). And make it into a function.

function includeAllInDirectory($directory)
{
    if (!is_dir($directory)) {
        return false;
    }

    // Make sure to add a trailing slash
    $directory = rtrim($directory, '/\\') . '/';

    foreach (glob("{$directory}*.php") as $filename) {
        require_once($directory . $filename);
    }

    return true;
}
like image 179
Znarkus Avatar answered Oct 04 '22 01:10

Znarkus


This is fairly simple. See arrays and foreach.

$dirs = array(FRAMEWORK_GENERAL, FRAMEWORK_PLUGINS, );

foreach ($dirs as $dir) {
    $d = opendir($dir);

    while (($file = readdir($d)) !== false) {
        if(strpos($file,'.php')) {
            include_once($dir . $file);       
        }       
    }

    closedir($d);
}
like image 35
Artefacto Avatar answered Oct 04 '22 01:10

Artefacto