0

I have typed the following code in PHP to read the text "yusuf123" from the external text file called "sample.txt" and to count and print the total number of digits. The code is surprisingly counting 4 digits instead of 3.

$file = fopen("sample.txt", "r");
$count = 0 ;
while(!feof($file))
{
  $ch = fgetc($file);
  if($ch >= '0' && $ch <= '9')
   $count++;
}
echo $count ;
fclose($file);

?>

The output of the above code is 4 instead of 3. Kindly help me resolving this. Thanks in advance

Yusuf M
  • 27
  • 3
  • 6
  • 1
    Why not try the `is_numeric($ch)` function instead of `($ch >= '0') && ($ch <= '9')`? See: http://php.net/manual/en/function.is-numeric.php – KIKO Software Apr 23 '18 at 08:18
  • 1
    The EOF is probably being counted as 0. You might want to check PHP's manual on the topic of type juggling – GordonM Apr 23 '18 at 08:22
  • thank u for ur answer. I have to teach students as per their syllabus and is_numeric() is not there. Any other way? – Yusuf M Apr 23 '18 at 08:25
  • If you added `print (integer)$offset++ . " " . ord($ch) . "\n";` it might give you some clues. – symcbean Apr 23 '18 at 08:30

2 Answers2

1

You can use file_get_contents and read the whole file as one string and use preg_match_all to get all digits.

//$str = file_get_contents("sample.txt");
$str = "yusuf123";

preg_match_all("/\d/", $str, $digits);
echo count($digits[0]); // 3

https://3v4l.org/tnaX1

Not sure it will solve your issue as I can't test on the file you have, but it works here.
$digits[0] because it's an array with the matching digits.

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

Thanks for ur prompt assistance. I found the answer. I found that the variable retains the last value when EOF is reached and it is counted twice. This is what I did and i found the answer.

<?php
$file = fopen("sample.txt", "r");
$count = 0 ;
 $ch = fgetc($file);
while(!feof($file))
{ 
  if($ch >= '0' && $ch <= '9')
   $count++;  
$ch = fgetc($file);
}
 echo $count. " ". $ch. "<br>";
fclose($file);
?>
Yusuf M
  • 27
  • 3
  • 6