user622378
user622378

Reputation: 2346

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;
    echo "<br />";
  }
}
fclose($file_handle);
?>

Upvotes: 1

Views: 462

Answers (2)

Jason McCreary
Jason McCreary

Reputation: 73031

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 />";
  }

Upvotes: 6

deceze
deceze

Reputation: 522470

!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.

Upvotes: 5

Related Questions