如何在PHP中访问循环外的for循环变量?

时间:2015-05-22 05:41:53

标签: php for-loop

我在PHP中有一个for循环,想要在循环外访问$f变量。有没有办法做到这一点?我搜索了答案,但找不到合适的答案。

foreach($dirlist as $f) {

}

filemtime($f)

更新

我只是采用了更简单的方法,最终做到了这一点:

date('M d, Y', filemtime(getcwd().'/index.php'))

2 个答案:

答案 0 :(得分:2)

将您的filemtime结果添加到新数组,并按文件名检索上次修改日期。

<?php
// Array of modified dates, file names as keys
$modifiedDates = array();

foreach($dirlist as $f) {
  $modifiedDates[basename($f)] = filemtime($f);
}

// File name to look modified time again (just file name, no path)
// basename function gets file name from path
$filename = basename( $pathToFile );
$lastModified = $modifiedDates[$filename];
?>
<p class="post-info">This article was last reviewed on <?php echo '<time itemprop="dateModified" datetime="'.date('Y-m-d', $lastModified).'">'. date('M d, Y', $lastModified).'</time>'; ?></p>

答案 1 :(得分:0)

考虑以下伪代码

$yourMatchedFile = null;
foreach($dirlist as $f) {
    if($f is good enough!!) {
        $yourMatchedFile = $f;
        break;
    }
}

if(isset($yourMatchedFile)) {
     DoWhatever();
}