PHP 中的这行代码对目录有什么作用


what does this line of code in php do for directories

我无法弄清楚数组中存储的内容...任何人都可以解释一下。请以简单的方式解释。谢谢大家我已经从网络上尝试过,完整的代码在这里

<?php
$dhandle = opendir('.');
$files = array();
if ($dhandle) {
   while (false !== ($fname = readdir($dhandle))) {
      if (($fname != '.') && ($fname != '..') && ($fname != basename($_SERVER['PHP_SELF']))) { 
          // this if condition is confusing me
          $files[] = (is_dir( "./$fname" )) ? "(Dir) {$fname}" : $fname; 
          // and the above line too
      }
   }
   closedir($dhandle);
}
echo "<select name='"file'">'n";
foreach( $files as $fname )
{
   echo "<option>{$fname}</option>'n";
}
echo "</select>'n";
?>

这是我不明白的代码行

$files[] = (is_dir( "./$fname" )) ? "(Dir) {$fname}" : $fname;

这是一个三元语句,等于:

if(is_dir( "./$fname" )){
  $files[] = "(Dir) {$fname}";
} else {
  $files[] = $fname; 
}

这意味着基本上,如果变量包含一个目录,请将字符串 (Dir) 添加到前面,否则只需使用该变量。

这是三元运算器。

$variable = (condition) ? true : false;

是 的缩写

if (condition) {
    $variable = true;
} else {
    $variable = false;
}

. 是对当前目录的引用(在 Linux 中为 PWD)

..是这个目录之前的目录,在路径中

if (($fname != '.') && ($fname != '..') && ($fname != basename($_SERVER['PHP_SELF'])))意味着:

如果正在检查的文件名:
一个。不是当前目录的名称,并且
b.不是父目录的名称,并且
c.不是这个文件(脚本本身)

$files[] = (is_dir( "./$fname" )) ? "(Dir) {$fname}" : $fname;意味着:

  1. 添加到名为 $files
    数组
  2. 如果正在检查的文件是目录,请添加"(目录)文件名"
  3. 否则只需添加"文件名"