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:

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:

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:

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:

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.