Эти реализации действительно просты.
count
// count($a)
it works like `return a.length` in other languages.
array_count_values
// array_count_values(a)
// https://github.com/php/php-src/blob/683123fa39114692b712b8c88d5b2fec9b1fc7ea/ext/standard/array.c
// it works like this:
$r = [];
for($a as $v) {
$r[$v]++;
}
return $r;
substr_count
// substr_count(p, needle)
if (needle_len == 1) {
//if there is only one char in needle, just search it in the memory, more effective
cmp = needle[0];
while ((p = memchr(p, cmp, endp - p))) {
count++;
p++;
}
} else {
// just like C's strstr to search
while ((p = (char*)php_memnstr(p, needle, needle_len, endp))) {
p += needle_len;
count++;
}
}
//or PHP-like version
//remember: the strchr is strstr in PHP while they are different in C
//so just a demo here
$c = 0;
while($p = strstr($p, $needle)) {
// get the remaining string
// in C here is a pointer operation and much more faster
$p = substr($p, strlen($needle));
$c++;
}