Search code examples
phpreaddir

array_item[] = $file what does this do?


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

Solution

  • 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
              )
    )