# Optional Level Parameter for `dirname()`

> Section in “New and Extended Functionality › I/O and Filesystem” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/io-and-filesystem/optional-level-parameter-for-dirname/>

When working with the filesystem, PHP’s `dirname()` function is really handy. It returns the directory name extracted from the given file name, also known as the path:

``` php
var_dump(dirname('/path/to/the-file.txt'));
```

The result is:

    string(8) "/path/to"

In this example, the directory `/path/to` is the directory where the file `/path/to/the-file.txt` is located. The `dirname()` function can also be used multiple times:

``` php
var_dump(dirname(dirname('/path/to/the-file.txt')));
```

Now the result is:

    string(5) "/path"

In this example, `/path` is the parent directory of `/path/to`, which is the location of the file `/path/to/the-file.txt`.

PHP 7 adds a second, optional parameter to the `dirname()` function, that can be used to specify the number of levels to go up. So instead of calling `dirname()` twice, we can now write:

``` php
var_dump(dirname('/path/to/the-file.txt', 2));
```

The result, again, is:

    string(5) "/path"

The level, if specified, must be a positive integer value, otherwise PHP will issue a warning and return `NULL`:

``` php
var_dump(dirname('/path/to/the-file.txt', 0));
```

This will result in:

    Warning: dirname(): Invalid argument, levels must be >= 1 in ...
    NULL

One could argue that the original path should be returned instead, but this is not the case. Also note that the parent directory of the root directory `/` is considered to be `/` itself.

---

Previous: [Support for VT100 Console Mode](https://php7explained.com/new-and-extended-functionality/io-and-filesystem/support-for-vt100-console-mode/index.html.md) | Next: [Specifying the zip Compression Method](https://php7explained.com/new-and-extended-functionality/io-and-filesystem/specifying-the-zip-compression-method/index.html.md)
