0

I am trying to append filenames to an array in PHP. I have code which reads filenames from a directory "songs" on a server. I simply want each of these filenames to be added to an array. How could I do this?

Here is my PHP.

$target = "songs/"; 
$items = array();
if ($handle = opendir($target)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            foreach($song as $entry) {
                $items[] = $entry; 
            }

            //echo $items;
            echo $entry."\n";
        }
    }
    closedir($handle);
}
8
  • What isn't working with the code you have? What does $items look like after the while? Commented Apr 14, 2017 at 21:13
  • foreach($song as $entry) What is $song? Commented Apr 14, 2017 at 21:16
  • When I echo $items it returns "ArrayArrayArrayArray......" Stuck in loop. @SloanThrasher Commented Apr 14, 2017 at 21:17
  • You're using the same variable $entry for the filename and in foreach ($song as $entry). So after the loop, $entry contains the last element of $song, not the filename. Commented Apr 14, 2017 at 21:19
  • What does the database code at the top have to do with this? Commented Apr 14, 2017 at 21:19

1 Answer 1

1

You're using the same variable in the foreach loop as you're using to hold the filename from readdir(). So when you do $items[] = $entry; you're adding the iteration variable to the array, not the filename. There doesn't seem to be any reason to add the filename to the array inside the loop, and you should avoid reusing variables like that, it just causes confusion.

$items = array();
if ($handle = opendir($target)) {
    while ($entry = readdir($handle)) {
        if ($entry != "." && $entry != "..") {
            $items[] = $entry;
            foreach($song as $s) {
                // do something with $s
            }

            //echo $items;
            echo $entry."\n";
        }
    }
    closedir($handle);
}
Sign up to request clarification or add additional context in comments.

2 Comments

It seems I am still having trouble. I want each $entry to be appended to the array. @Barmar
This does append each $entry to the array, except for . and ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.