Reputation: 2346
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
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()
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
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