PHP dirname() | Get Path of Parent Directory

The PHP dirname() function is used when we need to get the path of the parent directory. For example:

<?php
   echo dirname("C:/xampp/htdocs/index.php");
?>

The output of the above PHP example is:

php dirname function

PHP dirname() Syntax

The syntax of the dirname() function in PHP is:

dirname(path, levels)

The second, or levels, parameter is optional. The default value of this parameter is 1. The levels parameter is used when we need to specify the number of directories to go up. For example:

<?php
   echo dirname("C:/xampp/htdocs/index.php", 1) . "<br>";
   echo dirname("C:/xampp/htdocs/index.php", 2) . "<br>";
   echo dirname("C:/xampp/htdocs/index.php", 3) . "<br>";
?>

This PHP code outputs the directory names for a given path using the dirname() function with the second argument specifying the number of parent directories to traverse up.

The first line of code invokes the dirname() function, passing it the path "C:/xampp/htdocs/index.php" as the first argument and 1 as the second. This means that the function will return the name of the directory one level up from the file "index.php." The following will be the end result:

C:/xampp/htdocs

The "br" is used to append a line break at the end of the output. Now the second line of code uses the same path as the previous line, but with the second argument set to 2. This means that the function will return the name of the directory two levels up from the file "index.php." The following will be the end result:

C:/xampp

This line of code calls the dirname() function with the same path as the previous lines, but with the second argument set to 3. This means that the function will return the directory name three levels up from the file "index.php". However, since there are only two levels of directories above "index.php", the dirname() function will return the root directory "C:/". The resulting output will be the following:

C:/

Advantages of the dirname() function in PHP

Disadvantages of the dirname() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »