Simple question on arrays

I’m working in PHP, though I’m less worried about syntax than I am about the concept.

I’m trying to read an array, and then store that information (and other info) in a new array. The relevant part of my code looks basically like this:



foreach($file as $file)
{
$songs = array(
    $file => array("band"=>$bandname, "song"=>$songname));
}


. . . but when I try to read the array $songs, I only get the info from the last iteration of the foreach. What am I missing here? Is $songs getting reset each time through the code? Do I need to set some sort of pointer to move to the next ‘slot’ of the array each time?

Your foreach loop is re-initialising $songs on each iteration.

I think you probably mean this:



foreach($file as $file)
{
$songs[ $file ] => array("band"=>$bandname, "song"=>$songname);
}


Yes, because you’re doing a new assignment each time through the loop, overwriting whatever was in $songs before.

In PHP, you can use the syntax $songs to assign to the next empty index in an array. So



$songs[] = array(
    $file => array("band"=>$bandname, "song"=>$songname));


Some other notes:

PHP is a really, fantastically shitty language, so you have to be extra careful to make things easy for your fellow programmers. It’s probably not a good idea to use the same name for your array and the loop variable ($file), which is very confusing. It’s not clear where $bandname and $songname are coming from; if they are keys in your $file array, a comment to that effect would go a long way.

Thanks guys. I didn’t realize there was a functional difference between $array and $array.

And, as far as commenting the file, don’t worry, they’re there. Just for me, since this is a private project, but I often go back to things a year or two later, and goodness knows I need documentation, as simple as any of my programming is. I think I will change the $file variable though . . . it is confusing, and I always have to do a double take when I look at it.

Basically, I’m taking an array of file names from a directory, parsing out the names of the band and the song (ie: Blue Oyster Cult - Don’t Fear The Reaper.mp3 becomes -> $bandname=Blue Oyster Cult, $songname=Don’t Fear The Reaper), and then printing out the list. I’m storing the info in an array, because I’d like to be able to sort/search on different array values, like list alphabetically based on the “band” value (that’s the bulk of the project . . . gotta see if I can figure it out!).