0

I have a for loop in PHP and want to access the $f variable outside the loop. Is there a certain way to do this? I searched for the answer but can't find the right one.

foreach($dirlist as $f) {

}

filemtime($f)

Update:

I just went the more simple way and ended up doing this:

date('M d, Y', filemtime(getcwd().'/index.php'))
9
  • Are you aware that the $f will be the last element in the array? Commented May 22, 2015 at 5:43
  • Which $f? Each iteration will have different $f. Commented May 22, 2015 at 5:44
  • Its not possible @Mike you will be getting only the last element from the array... Commented May 22, 2015 at 5:44
  • Why arent you using filemtime in loop? Could you clarify, what you want to achieve? Commented May 22, 2015 at 5:50
  • 1
    I think you are looping through that array to meet some criteria, and you want to access the matched one outside the loop, don't you? Commented May 22, 2015 at 5:52

2 Answers 2

2

Add your filemtime results to the new array and retrieve last modified date by file name.

<?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>
Sign up to request clarification or add additional context in comments.

4 Comments

I ended up simply using this date('M d, Y', filemtime(getcwd().'/index.php'))
But your question was not to use filemtime on this file again. Though your solution dosen't answer the question. I understand that this way worked for you, but you should stick to your question "How can I access the for-loop variable outside the loop in PHP?".
I would like to know how to but can't figure it out. So I did what was easier. My question seems pretty simple. I just want to know how to, after looping through the array to meet some criteria, then be able to access the matched one outside the loop?
Yes. I totally understand you. You did what was easier and it works well. Though I think I answered your question. With my solution, you can access this date outside of the loop.
0

Consider the following pseudo-code:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.