in PHP using 'if statement' to find a word
I have a text file with several lines of text, eg:
JOHN
MIKE
BEN
JAMES
PETE
I read that contents into an array, with each line of text, placed into a seperate element of the array.
I then tested each element of the array, to find a phrase, say 'BEN'
ie:
for( $a = 0; $a < 5; $a++ )
{
if ($contents[$a] == "BEN")
{
echo "$contents[$a]";
}
}
but this fails to recognise 'BEN'
but if I was looking for a number instead of a word, from:
JOHN
MIKE
10
JAMES
PETE
or from...
5
10
15
20
25
and used the same code, to look for the number, eg: say '10'
if ($contents[$a] == 1开发者_运维百科0)
{
echo "$contents[$a]";
}
then this works ok, so why ?
Also...
I dont get the problem if the individual lines of text, are already in the array, only when they are READ from the text file...
$contents[0] = "JOHN";
$contents[1] = "MIKE";
$contents[2] = "BEN";
$contents[3] = "JAME";
$contents[4] = "PETE";
I presume that the strings you read from the text file contain the trailing end-of-line character for each line, that's why you cannot find BEN
(since that string does not include the trailing end-of-line character). Use the trim
function to get rid of trailing whitespace in your strings before comparing them against strings.
Try using array_search()
if ($index = array_search('BEN', $contents) {
echo $contents[$index];
}
Probably because when you read line from file, you also have newline (\n
) character at the end of string. Use rtrim()
to strip it.
You should also check out strcmp()
for comparing strings in PHP.
精彩评论