Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it whenever I use scandir() I receive periods at the beginning of the array?

Tags:

directory

php

Why is it whenever I use scandir() I receive periods at the beginning of the array?

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)
like image 690
DividedDreams Avatar asked Aug 20 '11 14:08

DividedDreams


3 Answers

There are two entries present in every directory listing:

  • . refers to the current directory
  • .. refers to the parent directory (or the root, if the current directory is the root)

You can remove them from the results by filtering them out of the results of scandir:

$allFiles = scandir(__DIR__); // Or any other directory $files = array_diff($allFiles, array('.', '..')); 
like image 84
phihag Avatar answered Sep 27 '22 20:09

phihag


Those are the current (.) and parent (..) directories. They are present in all directories, and are used to refer to the directory itself and its direct parent.

like image 25
Mat Avatar answered Sep 27 '22 20:09

Mat


To remove . and .. from scandir use this function:

function scandir1($dir)
{
    return array_values(array_diff(scandir($dir), array('..', '.')));
}

The array_values command re-indexes the array so that it starts from 0. If you don't need the array re-indexing, then the accepted answer will work fine. Simply: array_diff(scandir($dir), array('..', '.')).

like image 20
Dan Bray Avatar answered Sep 27 '22 21:09

Dan Bray