1

i have a text file with colors in it. The script only returns true if orange is selected. What in the world am i missing?

$filename="colors.txt";
$words=file($filename);
shuffle($words);
$word=$words[0];


if ( $word == "yellow" ){$pid = '558';}
else if ( $word == "red" ){$pid = '557';} 
else if ( $word == "purple" ){$pid = '556';}
else if ( $word == "orange" ){$pid = '555';} 
else if ( $word == "green" ){$pid = '554';}
else if ( $word == "brown" ){$pid = '553';}
else if ( $word == "blue" ){$pid = '552';}
else {$pid = 'poop';}

echo $word;
echo $pid;

the text file for colors.txt

red
green
blue
yellow
brown
purple
orange
4

4 に答える 4

4

The "orange" line, being the last in the file, doesn't have a line ending "\r\n".

Form the documentation for file():

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.

于 2012-04-17T22:04:01.710 に答える
1

Each line from your text file also contains a carriage return and possibly a line feed. Change:

$word=$words[0];

to be:

$word=trim($words[0]);

should remove any trailing or leading spaces / CRs and your IF statement should then work correctly.

于 2012-04-17T22:04:39.423 に答える
0

Use this instead:

$words = file($filename, FILE_IGNORE_NEW_LINES);

By default, file() adds new lines to the end of each array item. The flag FILE_IGNORE_NEW_LINES keeps this from happening. An alternative way of achieving this would be to use rtrim() on each array item.

于 2012-04-17T22:04:47.877 に答える
0

Improve your line:

$words=file($filename);

to the following:

$words=file($filename,FILE_IGNORE_NEW_LINES);

Function won't add new line to each array element.

PHP function file()

P.S.: Each time you don't get the result you expect, just check documentation for every PHP function that is involved in your process. Maybe you have to read half a page for it, but still, you save time with it.

于 2012-04-17T22:08:13.663 に答える