array_item[] = $file what does this do?

720 Views Asked by At

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;               
        }
}
5

There are 5 best solutions below

1
On BEST ANSWER

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
          )
)
0
On

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.

0
On

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

0
On

$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...

1
On

$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