-1

I have to count the number of "a's" in the string:

$a = "aaa apple";

this is my code:

<?php
$file = fopen("count.txt","w");
$txt = "as a teacher i am addicted to apple";
fwrite($file,$txt);
fclose($file);
$file1 = fopen("count.txt","r");
$arr = substr_count("$file1","a");
echo $arr;
?>

however this returns 0.

which php function should i use?

hlscalon
  • 7,304
  • 4
  • 33
  • 40

1 Answers1

0

You are using

$arr = substr_count("$file1", "a");

instead of

$arr = substr_count($txt, $a);

Why do you need to write to a file before checking the number of occurrences?

If you want to get the content of the file again, use

$file1 = fopen("count.txt","r");
$contents = fread($file1, filesize("count.txt"));
fclose($file1);
$arr = substr_count($contents, $a);
cornelb
  • 6,046
  • 3
  • 19
  • 30