PHP 8.6.0 Beta 1 is available for testing

count_chars

(PHP 4, PHP 5, PHP 7, PHP 8)

count_charsDevuelve estadísticas sobre los caracteres utilizados en un string

Descripción

function count_chars(string $string, int $mode = 0): array |string

count_chars() cuenta el número de ocurrencias de todos los bytes presentes en el string string y devuelve diferentes estadísticas.

Parámetros

string

El string analizado.

mode

Ver los valores devueltos.

Valores devueltos

Según el valor de mode, count_chars() devuelve la siguiente información:

  • 0: un array con el byte como índice y la frecuencia correspondiente para cada byte.
  • 1: idéntico a 0, pero solo se listan las frecuencias mayores que cero.
  • 2: idéntico a 0, pero solo se listan las frecuencias nulas.
  • 3: un string que contiene todos los bytes utilizados es devuelto.
  • 4: un string que contiene todos los bytes no utilizados es devuelto.

Historial de cambios

Versión Descripción
8.0.0 Anterior a esta versión, la función devolvía false en caso de error.

Ejemplos

Ejemplo #1 Ejemplo con count_chars()

<?php
$data = "Deux D et un F.";
foreach (count_chars($data, 1) as $i => $val) {
 echo "Hay $val ocurrencia(s) de \"" , chr($i) , "\" en la frase.\n";
}
?>

El ejemplo anterior mostrará:

Hay 4 ocurrencia(s) de " " en la frase.
Hay 1 ocurrencia(s) de "." en la frase.
Hay 2 ocurrencia(s) de "D" en la frase.
Hay 1 ocurrencia(s) de "F" en la frase.
Hay 2 ocurrencia(s) de "e" en la frase.
Hay 1 ocurrencia(s) de "n" en la frase.
Hay 1 ocurrencia(s) de "t" en la frase.
Hay 2 ocurrencia(s) de "u" en la frase.
Hay 1 ocurrencia(s) de "x" en la frase.

Véase también

  • strpos() - Busca la posición de la primera ocurrencia en un string
  • substr_count() - Cuenta el número de ocurrencias de segmentos en un string

Found A Problem?

Learn How To Improve This PageSubmit a Pull RequestReport a Bug
+add a note

User Contributed Notes 8 notes

up
26
marcus33cz
14 years ago
If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode "1" of the original function.
<?php
/**
 * Counts character occurences in a multibyte string
 * @param string $input UTF-8 data
 * @return array associative array of characters.
 */
function mb_count_chars($input) {
 $l = mb_strlen($input, 'UTF-8');
 $unique = array();
 for($i = 0; $i < $l; $i++) {
 $char = mb_substr($input, $i, 1, 'UTF-8');
 if(!array_key_exists($char, $unique))
 $unique[$char] = 0;
 $unique[$char]++;
 }
 return $unique;
}
$input = "Let's try some Greek letters: αααααΕεΙιΜμΨψ, Russian: ЙЙЫЫЩН, Czech: ěščřžýáíé";
print_r( mb_count_chars($input) ); 
//returns: Array ( [L] => 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [α] => 5 [Ε] => 1 [ε] => 1 [Ι] => 1 [ι] => 1 [Μ] => 1 [μ] => 1 [Ψ] => 1 [ψ] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [Й] => 2 [Ы] => 2 [Щ] => 1 [Н] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [ě] => 1 [š] => 1 [č] => 1 [ř] => 1 [ž] => 1 [ý] => 1 [á] => 1 [í] => 1 [é] => 1 )
?>
up
2
Eric Pecoraro
21 years ago
<?php
// Require (n) unique characters in a string
// Modification of a function below which ads some flexibility in how many unique characters are required in a given string.
$pass = '123456' ; // true
$pass = '111222' ; // false
req_unique($pass,3);
function req_unique($string,$unique=3) {
 if ( count(count_chars($string,1)) < $unique) {
 echo 'false';
 }else{
 echo 'true';
 }
}
?>
up
2
seb at synchrocide dot net
22 years ago
After much trial and error trying to create a function that finds the number of unique characters in a string I same across count_chars() - my 20+ lines of useless code were wiped for this:
<?
function unichar($string) {
$two= strtolower(str_replace(' ', '', $string));
$res = count(count_chars($two, 1));
return $res;
}
/* examples :: */
echo unichar("bob"); // 2
echo unichar("Invisibility"); //8
echo unichar("The quick brown fox slyly jumped over the lazy dog"); //26
?>
I have no idea where this could be used, but it's quite fun
up
1
Anonymous
10 years ago
count_chars for multibyte supported.
<?php
function mb_count_chars ($string, $mode = 0) {
 
 $result = array_fill(0, 256, 0);
 
 for ($i = 0, $size = mb_strlen($string); $i < $size; $i++) {
 $char = mb_substr($string, $i, 1);
 if (strlen($char) > 1) {
 continue;
 }
 
 $code = ord($char);
 if ($code >= 0 && $code <= 255) {
 $result[$code]++;
 }
 }
 
 switch ($mode) {
 case 1: // same as 0 but only byte-values with a frequency greater than zero are listed.
 foreach ($result as $key => $value) {
 if ($value == 0) {
 unset($result[$key]);
 }
 }
 break;
 case 2: // same as 0 but only byte-values with a frequency equal to zero are listed.
 foreach ($result as $key => $value) {
 if ($value > 0) {
 unset($result[$key]);
 }
 }
 break;
 case 3: // a string containing all unique characters is returned.
 $buildString = '';
 foreach ($result as $key => $value) {
 if ($value > 0) {
 $buildString .= chr($key);
 }
 }
 return $buildString;
 case 4: // a string containing all not used characters is returned.
 $buildString = '';
 foreach ($result as $key => $value) {
 if ($value == 0) {
 $buildString .= chr($key);
 }
 }
 return $buildString;
 }
 
 // change key names...
 foreach ($result as $key => $value) {
 $result[chr($key)] = $value;
 unset($result[$key]);
 }
 
 return $result;
 
}
?>
up
0
Andrey G
6 years ago
Checking that two strings are anagram:
<?php
function isAnagram($string1, $string2)
{
 return count_chars($string1, 1) === count_chars($string2, 1);
}
isAnagram('act', 'cat'); // true
?>
up
0
pzb at novell dot com
19 years ago
This function is great for input validation. I frequently need to check that all characters in a string are 7-bit ASCII (and not null). This is the fastest function I have found yet:
<?php
function is7bit($string) {
 // empty strings are 7-bit clean
 if (!strlen($string)) {
 return true;
 }
 // count_chars returns the characters in ascending octet order
 $str = count_chars($str, 3);
 // Check for null character
 if (!ord($str[0])) {
 return false;
 }
 // Check for 8-bit character
 if (ord($str[strlen($str)-1]) & 128) {
 return false;
 }
 return true;
}
?>
up
-2
mlong at mlong dot org
24 years ago
// Usefulness of the two functions
<?php
 $string="aaabbc";
 // You just want to count the letter a
 $acount=substr_count($string,"a");
 // You want to count both letter a and letter b
 $counts=count_chars($string,0);
 $acount=$counts[ord("a")];
 $bcount=$counts[ord("b")];
?>
up
-3
phpC2007
18 years ago
Here's a function to count number of strings in a string. It can be used as a simple utf8-enabled count_chars (but limited to a single mode)...
<?php
function utf8_count_strings($stringChar)
{
 $num = -1;
 $lenStringChar = strlen($stringChar);
 
 for ($lastPosition = 0; 
 $lastPosition !== false;
 $lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
 {
 $num++;
 }
 
 return $num;
}
?>
+add a note

AltStyle によって変換されたページ (->オリジナル) /