Home > Software design >  Count strpos() Occurences
Count strpos() Occurences

Time:01-29

How can I count found occurrences of a keyword? Currently I have this

$filesfound = false;
foreach ($arr as $file)
$filesfound = true;
...
echo $vouchers = ($filesfound === true) && (strpos(implode('/', $file), 'Voucher') !== false) ? '<div>  2 Files Available</div>' : '';

I am trying to get " 2 files available" to actually account for the string occurences found. How can I do this? Multiple functions give no result I am expecting. In this case, I am expecting a correct read of 2

Thanks!!


SOLUTION

$filesfound = false;
foreach ($arr as $file) {
   // If occurrences were found. Returns 0 for each match, so we add   1
   if (strpos(implode('/', $file), 'Voucher') === 0) { 
      $filesfound = true;
      $count = $count   1; 
   } 
}
echo $count;

CodePudding user response:

To count occurrences of a text within a string, you can use:

$text = 'This is a test';
// find how many "is" are within our $text variable:
echo substr_count($text, 'is'); // this will return 2, since there are 2 of "is" in our $text
  •  Tags:  
  • Related