开发者

is_numeric does not work when reading from txt file?

In a text file I have a file like this:

Olivia
7

Sophia
8

Abigail
9

Elizabeth
10

Chloe
11

Samantha
12

I want to print out all the name only and ignore the numbers.

For some reason, it dont work - it wouldn't print anything?

<?php
$file_handle = fopen("names.txt", "rb");
while (!feof($file_handle) ) {
  $line_of_text = fgets($file_handle);
  if (!is_numeric((int)$line_of_text)) { 
    echo $line_of_text;
    e开发者_开发问答cho "<br />";
  }
}
fclose($file_handle);
?>


You are casting every line with (int). So even lines that are strings will become 0 (zero).

You can change your code to:

!is_numeric($line_of_text)

Note: is_numeric() will return true for decimals and scientific notation also. If you are strictly determining if the line contains digits, I suggest ctype_digit()

UPDATE

You will also need to trim($line_of_text) as fgets() includes the newline.

Code inside while():

  $line_of_text = trim(fgets($file_handle));
  if (!ctype_digit($line_of_text)) { 
    echo $line_of_text;
    echo "<br />";
  }


!is_numeric((int)$line_of_text)

Think about it: You're casting the line to an int, so whatever it was before, it'll become a number. Then you're testing whether it's not numeric. Of course it'll be numeric, because you made it so. Hence the condition will always be false.

Stop casting to int before testing for is_numeric.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜