By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,376 Members | 3,024 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,376 IT Pros & Developers. It's quick & easy.

Printing only two lines from a file

P: n/a
Hi all!

I have a file (file01, i.e) like this:

foo
foo
foo
bar
foo
bar
foo

....

Where foo and bar repeats n times, but only foo and bar. What i want to
print is just:
foo
bar
I have tried this:

$myfile=file("file01");

$current_line = reset($myfile);
$first_line = $current_line;

print("First line is: $first_line");

while ($current_line=next($myfile))
{
if ($current_line != $first_line)
{
print("The other line is: $current_line");
break;
}
}
and it works as stand alone, but in the real application, i get:

Fatal error: Cannot break/continue 1 level in
/var/www/html/web/include/functionShow.inc on line 172
Does anyone knows how to do it in another way?

Thanks a lot.

Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Fernando Alvarez-Uria wrote:
Hi all!

I have a file (file01, i.e) like this:

foo
foo
foo
bar
...

Where foo and bar repeats n times, but only foo and bar. What i want to
print is just:

foo
bar .... Does anyone knows how to do it in another way?


Try this:

<?php
unset($x);
$fh = fopen('file01', 'r');
while (!feof($fh)) { // read the file line-by-line
$line = trim(fgets($fh));
if ($line) $x[$line]++; // and increment a count for each line
}
fclose($fh);
echo "lines in file (hopefully by order of appearance):\n------------\n";
foreach ($x as $line=>$count) {
echo "[$line] shows up $count times\n"; // display the line and count
// echo "$line\n"; // display just the line
}
echo "------------\n";
?>
--
--= my mail box only accepts =--
--= Content-Type: text/plain =--
--= Size below 10001 bytes =--
Jul 17 '05 #2

P: n/a
"Fernando Alvarez-Uria" a écrit le 12/12/2003 :
Hi all! Hi
I have a file (file01, i.e) like this:
foo
foo
foo
bar
foo
bar
foo
...

Where foo and bar repeats n times, but only foo and bar. What i want to print

I have tried this: [...] Does anyone knows how to do it in another way?


Try to use array_unique on your $myfile var :
$resultarray = array_unique(file("file01"));
Then parse $resultarray :
foreach ($resultarray AS $key => $val) {
echo "Distinct line number $key = $val<br>\n";
}

See the doc :
http://fr.php.net/manual/en/function.array-unique.php

--
Have you read the manual?
http://www.php.net/manual/en/

Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.