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);
?>
You are casting every line with
(int). So even lines that are strings will become0(zero).You can change your code to:
Note: is_numeric() will return
truefor 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():