0

I have been following a tutorial on readdir(), is_dir() etc involved in setting up a small image gallery based on folders and files on my FTP. I was wondering what the $directorys[] = $file; part does specifically?

while( $file= readdir( $dir_handle ) )      
{
        if( is_dir( $file ) ){              
            $directorys[] = $file;          
        }else{                              
            $files[] = $file;               
        }
}
crmepham
  • 4,676
  • 19
  • 80
  • 155

5 Answers5

3

$directory is an array.

The code

$directory[] = $file

adds $file to the end of $directory array. This is the same as

array_push($directory, $file).

More info at array_push at phpdocs

usoban
  • 5,428
  • 28
  • 42
  • 1
    So your code reads in a list of files/folders, and sorts them into two arrays: $directorys and $files – MrGlass Jan 09 '12 at 20:26
2

$file will contain the name of the item that was scanned. In this case, the use of is_dir($file) allows you to check that $file in the current directory is a directory or not.

Then, using the standard array append operator [], the $file name or directory name is added to a $files/$directorys array...

Mathieu Dumoulin
  • 12,126
  • 7
  • 43
  • 71
1

It adds the directory to the directory array :)

    if( is_dir( $file ) ){              
        $directorys[] = $file; // current item is a directory so add it to the list of directories       
    }else{                              
        $files[] = $file; // current item is a file so add it to the list of files
    }

However if you use PHP 5 I really suggest using a DirectoryIterator.

BTW naming that $file is really bad, since it isn't always a file.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
1

It pushes an item to the array, instead of array_push, it would only push one item to the array.

Using array_push and $array[] = $item works the same, but it's not ideal to use array_push as it's suitable for pushing multiple items in the array.

Example:

Array (
)

After doing this $array[] = 'This works!'; or array_push($array, 'This works!') it will appear as this:

Array (
   [0] => This works!
)

Also you can push arrays into an array, like so:

$array[] = array('item', 'item2');

Array (
   [0] => Array (
             [0] => item
             [1] => item2
          )
)
MacMac
  • 34,294
  • 55
  • 151
  • 222
0

It creates a new array element at the end of the array and assigns a value to it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335