This does not work with multibyte characters!
In the post condition could simply do:
$string = 'ddddeeeeeefffffffffgggggggggggggggggghhhhh';
$QntPorCaractere = count_chars($string, 1);
arsort($QntPorCaractere);
reset($QntPorCaractere);
echo strpos($string, key($QntPorCaractere));
Try this.
This will return the position of the first one of the most repeating letter in the string. That is, if it is gabcdefggg
it would be 0
, because g
is the one that repeats the most and the first position of g
is 0
.
The count_chars
using the 1
parameter will return exactly the number of occurrences (in the value) and what was the character (in the key) of the array, that is:
array(5) {
[100]=>
int(4)
[101]=>
int(6)
[102]=>
int(9)
[103]=>
int(18)
[104]=>
int(5)
}
In this case, the 103
is the g
, in the ASCII table, so we can sort, after all we want the one that has more occurrences, we use arsort()
.
Then we get the 103
, which is contained in the array key using key($QntPorCaractere)
and we use it inside the strpos()
that takes the first occurrence.
It may seem wrong to use strpos($string, 103);
instead of using something like strpos($string, pack('C', 103));
. But the PHP manual says "If needle is not a string, it is converted to an integer and applied to the ordinal value of a character.", So since it is in the int format the 103
passes to g
internally by strpos
.