I'm trying to make a function that gets a list of files from a directory, adds them and their names + extensions as elements of an array, and returns the array (the array's name is also set as a parameter in the function. This is what I have so far:
I simply get nothing. Well, I know that it's not stopping at 'if($col1List !== false) because the table is being echoed, but it seems that the loop adding files to the array simply isn't working.
1. use the PHP tags (instead of CODE tags) when you post php-code It applies colourcoding which makes the examples a lot easier to read
2. You are passing a string as the second argument to your function which you then use as the name for a local variable. Why are you doing that? It is making your code more complex than is necessary. Just remove the second argument entirely from the function and simply create a local variable (with any given name - this does not matter at all, as long as it's descriptive) in your function.
3. decide what the responsibilities are of your function. In my opinion it should list the contents of a directory based on a valid path. that leaves three outcomes:
a) a valid path is passed, but there is nothing in it: i think in this case it should return an empty array
b) a valid path is passed, and there are files in it: in this case it should return an array with elements
c) an invalid or inaccessible path is passed: in this case you could decide to throw an exception instead of return false, since an exception will be able to tell you what the problem was (path doesn't exist or path is not readable)
This will already give you more control when something goes wrong since you will know exactly what the problem is.
apart from that:
- your code does not compensate for "." and ".." and neither does it take into account that a directory might contain sub-directories
- you code assumes every file has an extension, which is not always the case
-
PHP Code:
foreach($col1List as $num => $key) {
echo "<td>".$col1List[$num]['name']
can be simply written as
PHP Code:
foreach($col1List as $num => $key) {
echo "<td>".$key['name']
- if you want to know exactly what the function returns, use:
PHP Code:
var_dump($col1List)
- i would put return $$name; directly after the while-loop, since that is the logical point to return it. It's not a big deal, but it makes the code more readable. (that is apart from the fact that you should change $$name like i mentioned above)
Bookmarks