I'm still learning php and I have tried implementing similar functions that I have seen on this site but can't get any of them to work. What I want to do is basic and I thought I should have it but can't get it.
Basically I want to return a count of the number of times a string appears in an array.
Here is what I have been trying. It keeps giving me 0, but should be returning 4 as there are 4 entries that have a logoutTime with May in them. Thanks in advance for and guidance. When I try to echo or print $maycount I'am just getting 0.
<?php
function MayVPNCount($searchVPNArrayResults, $may){
$may = 'may';
$maycount = 0;
foreach($vpnSessionArray as $oneVPNSession){
if (strpos($oneVPNSession->logoutTime, $may) !== false)
$maycount += 1;
}
return($maycount);
}
?>
Maybe you need something like this:
function MayVPNCount($searchVPNArrayResults, $may){
//in this case $searchVPNArrayResults is where Im going to look
//$may is what Im looking for.
$text = $searchVPNArrayResults;
$stringIMlooking = $may;
$position = 0;
$maycount = 0;
//stripos() intead of strpos() for case insensive
while (($position = strpos($text, $stringIMlooking, $position ))!== false) {
$position = $position + strlen($stringIMlooking);
$maycount++;
}
return $maycount;
}
echo MayVPNCount("the whole text one two tree for one five", "one");
you need to change the variables. If you have an array, you could use implode() function to get one string.
As @rickdenhaan said, substr_count() is better:
function MayVPNCount($searchVPNArrayResults, $may){
$text = $searchVPNArrayResults;
$stringIMlooking = $may;
//case sensitive
return substr_count($text, $may) ;
//case insensituve:
//return substr_count(strtoupper($text),strtoupper($may));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.