...

View Full Version : file() new line problem?



gazsux
01-08-2004, 05:50 PM
Hello,

All I am wanting to do is compare to arrays of strings and filter out one set of strings from the other. Like you may want to filter out a list of staff members names from a list of random people and staff members.

I have a staff text file, it contains:

ione
becs
glitterkat
jibbi
chelseaboy
dany
gazsux
dionysus

I have a list text file, it conatains:

ione
Camel
max
CIACodeName
Disturbed
Explicit
frekka
Frekkeh
gazsux
Habbex
Investigations.
NewsContact
pete

I have the code:


<?php

$file=file("file/list.txt");
$staff=file("file/staff.txt");

$result = array_diff($file, $staff);
foreach($result as $name) {
echo "$name<br>";
}

?>

However, the result I get is:

ione
Camel
max
CIACodeName
Disturbed
Explicit
frekka
Frekkeh
gazsux
Habbex
Investigations.
NewsContact
pete

I cant figure out why! is it to do with \n chars being bought in using file()? How can I make it just list non-staff names. The desired result is:

Camel
max
CIACodeName
Disturbed
Explicit
frekka
Frekkeh
Habbex
Investigations.
NewsContact
pete

I would appreciate any help, cheers

mordred
01-08-2004, 06:16 PM
If I change the order of the parameters used in array_diff() of your sample code, I do get your desired results.

$result = array_diff($staff, $file);

gazsux
01-08-2004, 10:08 PM
If I do that then I get the opposite of what I want, I get:

ione
becs
glitterkat
jibbi
chelseaboy
dany
gazsux
dionysus

They are the staff names I want to be removed.

However, I tried using array_intersect() to do the opposite and that doesn't work either... :(

mordred
01-09-2004, 12:03 AM
Looks like you're right with your assumptions that newlines (maybe of different filesystems?) are screwing up array_diff(). I don't know what happened with my first try, maybe I named the files incorrectly. Anyway, with PHP 4.3.4 on w2k I get your desired result after applying trim() on each line:



$list = array_map("clean", file("list.txt"));
$staff = array_map("clean", file("staff.txt"));

function clean($value) {
return trim($value);
}
$result = array_diff($list, $staff);

foreach($result as $name) {
print "$name\n";
}


hth

gazsux
01-09-2004, 12:20 AM
Top man! :thumbsup:

Cheers for the help mate, it works!

I think I will look into alternatives to file() I have had a few probs with it before relating to \n.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum