Unless it is an object, count casts its argument to an array, and
count((array) "example")
= count(array("example"))
= 1
Answer from phihag on Stack OverflowUnless it is an object, count casts its argument to an array, and
count((array) "example")
= count(array("example"))
= 1
A string is an array of characters in C, C++ and Java. In PHP, it is not.
Remember that PHP is a very loose language, you can probobly get a character from a PHP string with the []-selector, but it still dosn't make it an array.
You don't have to convert that into an array() you can use substr_count() to achieve the same.
substr_count โ Count the number of substring occurrences
<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c');
?>
PHP Manual
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
EDIT:
Sorry for the misconception, you can use count_chars to have a counted value of each character in a string. An example:
<?php
$str = "cdcdcdcdeeeef";
foreach (count_chars(
strr => $value) {
echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
PHP Manual: count_chars
count_chars โ Return information about characters used in a string
There is a php function that returns information about characters used in a string: count_chars
Well it might not be what you are looking for, because according to http://php.net/manual/en/function.count-chars.php it
Counts the number of occurrences of every byte-value (0..255) in string and returns it in various ways
Example from same link (http://php.net/manual/en/function.count-chars.php):
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as
val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
It is possible with substr_count().
I think you are not passing a value to it properly. Try it like this:
$string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
echo substr_count($string, 'K-1'); //echo's 1
echo substr_count($string, 'K'); // echo's 2
A possible solution using regular expression:
function get_num_chars($char) {
$string = '120201M, 121212M-1, 21121212M, 232323M-2, 32323K, 323232K-1';
return preg_match_all('/'.$char.'(?=,|$)/', $string, $m);
}
echo get_num_chars('M'); // 2
echo get_num_chars('M-1'); // 1
echo get_num_chars('M-2'); // 1
echo get_num_chars('K'); // 1
echo get_num_chars('K-1'); // 1