I created a function to count and display the number of files in a directory but it does not work.
The function :
<?php
function nnndir($dirx)
{
$direx=opendir("$dirx");
$nfiles=0;
while($filexx=readdir($direx))
{
if ($filexx!="." && $filexx!=".." && $filexx!="config.dat")
{
$nfiles++;
}
}
closedir($direx);
$num_f="Number of Files it´s : ".$nfiles."";
global $num_f;
}
nnndir("".$ruta_path_adm."".$ruta_db."/db_register");
echo $num_f;
?>
The number should be displayed, but it usually doesn't. However, it seems to work intermittently. How can I correct this?
When a function terminates, all its local variables disappear. $num_f
disappears after }
, global shouldn't be used for that. You should use a return value :
<?php
function nnndir($dirx)
{
$direx=opendir("$dirx");
$nfiles=0;
while($filexx=readdir($direx))
{
if ($filexx!="." && $filexx!=".." && $filexx!="config.dat") $nfiles++;
}
closedir($direx);
return $nfiles;
}
echo "Number of files : " . nndir("".$ruta_path_adm."".$ruta_db."/db_register");
?>
By the way, you don't need to write this function :
$number_of_files = count(scandir("".$ruta_path_adm."".$ruta_db."/db_register")) - 2;
scandir
returns an array containing the content of a directory. I use count()
to get the number of elements, and substract 2 for .
and ..
.
<¿php
function count_files($dir)
{
$files = scandir($dir);
return count($files) - 2; // We remove 2, "." and ".." occurences
}
$num_files = count_files("".$ruta_path_adm."".$ruta_db."/db_register");
echo "Number of files: {$num_files}";
// For having an array of filenames, just call:
// $filesArray = scandir("".$ruta_path_adm."".$ruta_db."/db_register");
?>
A better approach (to avoid calling scandir() twice) is the function to analyze the directory and return all the data at once.
<¿php
function analyze_dir($dir)
{
$ret = array();
$ret['filelist'] = scandir($dir);
$ret['num_files'] = count($ret['filelist']) - 2; // We remove 2, "." and ".." occurences
return $ret;
}
$data = analyze_dir("".$ruta_path_adm."".$ruta_db."/db_register");
echo "Number of files: {$data['num_files']}";
// The array of filenames is $data['filelist']
?>