What is the is_dir() function in PHP?

The is_dir() function in PHP checks whether the given filename is a directory.

Syntax

is_dir(string: $name):bool

Parameters

name: This specifies the path to the file we want to check.

Return value

is_dir() returns true if the provided filename exists and is also a directory. Otherwise, it returns false.

Code

The following code shows the use of the is_dir() function.

main.php
test.txt
<?php
$file = "test.txt";
mkdir("documents");
if(is_dir($file))
{
echo ("$file is a directory");
}
else
{
echo ("$file is not a directory");
}
echo "\n";
if(is_dir("documents"))
{
echo ("Documents is a directory");
}
else
{
echo ("Documents is not a directory");
}
?>

Explanation

In the code above, the file test.txt is passed to the function. Since it is not a directory, is_dir() returns false.

The mkdir function makes a directory named documents and returns true when it is checked using the is_dir() function.

This function produces cache output. We have to clear the cache by using the clearstatcache() function.

Copyright ©2024 Educative, Inc. All rights reserved