foreach loop

Hi All,

I’m having trouble with a foreach loop from a text file. I have a directory tree, and a list of these directories in a text file, i want to check the tree against the list, and echo if any directories are missing, the problem that i’m having is that i can’t seem to account for a new line, so if the file has 1 line, then it returns that it exists, but if the file has two line it returns the first as missing and the second as existing, even if it’s the same entry twice in the file - see code below for clarification

[php]

<?php $logFile = 'LogFile.txt'; $rootDirectory = 'C:\testdir\\'; $verificationFile = 'verificationfiles/directoryverification.txt'; $verificationContents = file($verificationFile); $fh = fopen($logFile,'a') or die("can't open file"); $new_line = "\r\n"; foreach($verificationContents as $directoryName) { $subDirectory = $rootDirectory.$directoryName; echo "$subDirectory
"; if (file_exists($subDirectory)) { echo "$subDirectory Exists
"; } else { echo "$subDirectory Does Not Exist
"; $libverificationfailed = 'failed'; fwrite($fh, "$subDirectory Not Found"); fwrite($fh, $new_line); } } ?>[/php]

So, as an example, the root directory has 2 subdirectories, subdir1 and subdir2.

directoryverification.txt looks like;
subdir1
subdir2

and the page echos;
C:\testdir\subdir1
C:\testdir\subdir1 Does Not Exist
C:\testdir\subdir2
C:\testdir\subdir2 Exists

So if there is a new line after the data in the text file, the code isn’t reading it correctly. I’m hoping that this makes sense and that somebody can help.

regards,

file(), by default, includes the new-line with the data. See the documentation for file() at php.net, and add the 2nd flag parameter to ignore the new-line characters -

FILE_IGNORE_NEW_LINES Do not add newline at the end of each array element
Sponsor our Newsletter | Privacy Policy | Terms of Service