What are some best practices for extracting a common directory from two file paths in PHP?

When working with file paths in PHP, it is common to need to extract a common directory from two paths. One way to do this is by using the `dirname()` function in PHP to get the directory of each path, then comparing the directories to find the common directory. By finding the common directory, you can easily determine the shared location between the two paths.

$path1 = '/path/to/file1.txt';
$path2 = '/path/to/subdirectory/file2.txt';

$dir1 = dirname($path1);
$dir2 = dirname($path2);

$commonDir = '';
$dirParts1 = explode('/', $dir1);
$dirParts2 = explode('/', $dir2);

foreach ($dirParts1 as $key => $dirPart) {
    if ($dirPart == $dirParts2[$key]) {
        $commonDir .= $dirPart . '/';
    } else {
        break;
    }
}

echo "Common directory: " . $commonDir;