Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count the occurrences of all the letters in a string PHP

Tags:

arrays

string

php

I want to count the frequency of occurrences of all the letters in a string. Say I have

$str = "cdcdcdcdeeeef";

I can use str_split and array_count_values to achieve this.

array_count_values(str_split($str));

Wondering if there is another way to do this without converting the string to an array? Thanks

like image 324
Wild Widow Avatar asked Sep 06 '15 06:09

Wild Widow


People also ask

How do I count letters in a string in PHP?

The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.

How do you count occurrences in a string?

One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

How do I count repeated words in a string in PHP?

You can use PHP's substr_count() function to find out how many times a given substring appears or is repeated in a string.

What is Strstr PHP?

The strstr() function searches for the first occurrence of a string inside another string. Note: This function is binary-safe. Note: This function is case-sensitive. For a case-insensitive search, use stristr() function.


1 Answers

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($str, 1) as $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

like image 54
DirtyBit Avatar answered Oct 05 '22 01:10

DirtyBit