Jump to content

Stopping the for loop with break


booxvid

Recommended Posts

I just want my program to print those array until the period exist.

 

<?php 
$filename = 'txt_files/read_this.txt';
$file_handle = file($filename);

for($i=0;$i<count($file_handle);$i++)
{
	if($file_handle[$i]=="."){

		break;
	}
	else{
		echo $file_handle[$i];
	}
}

//fclose($file_handle);
?>	

 

here's the content of my text file.

 

this

your

queen

nice

doll

.

you

are

 

it should stop reading the file when the loop meets '.' or the period i mean.

but it still print out the "you are" words ..

 

I already use the break statement, bu still...

Link to comment
https://forums.phpfreaks.com/topic/266267-stopping-the-for-loop-with-break/
Share on other sites

Most probably you'll need to trim() the lines before checking their contents. There may be spaces before or after the dot, so it doesn't return true when compared to "."

 

The following code works fine. I used a foreach() instead of a for().

 

<?php
$lines = file('txt_files/read_this.txt');

foreach ($lines as $line)
{
if (trim($line) == '.') break;

echo $line;
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.