count the occurrences of all the letters in a string PHP
Asked Answered
P

5

11

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

Pottage answered 6/9, 2015 at 6:49 Comment(0)
E
18

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

Emeldaemelen answered 6/9, 2015 at 6:56 Comment(1)
not the answer I'm looking for. I want to count all the occurrences of each letter in the string, not just a particular letter. :)Pottage
P
2

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 $i => $val) {
   echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
Profant answered 6/9, 2015 at 7:2 Comment(0)
N
1
class Strings
{
    public function count_of_each_letter($string){
        $string_chars = array();
        $length_ = mb_strlen($string,'UTF-8');
        if($length_== 0){return null;}
        else{
            for ($i=0; $i < $length_; $i++) { 
                $each_letter = mb_substr($string,0,1,'UTF-8');
                $string_chars[$each_letter] = mb_substr_count($string, $each_letter);
                $string = str_replace($each_letter,"", $string);
                $length_ = mb_strlen($string,'UTF-8');          
            }
            $string = '';
            foreach ($string_chars as $key => $value) { 
                $string .= $key.'-'.$value.'<br>';
            }
            return $string;
        }
    }
}
$new_counter  = new Strings();
echo $new_counter::count_of_each_letter('ختواجرایآهنگبهصورتتکنفرهنمود.اوازسال۱۹۷۲تا۱۹۷۵،۴آلبوماستودیوییتک‌نفرهمنتشرکردوحتینامزدیکجایزهاسکارهمشد.درهمینسال‌هاگروهاقدامبهبرگزاریتورکنسرتدراروپاونیزیکتورجهانیکردند.جکسونفایودرسال۱۹۷۵ازشرکتنشرموسیقیموتاونرکوردزبهسی‌بی‌اسرکوردزنقلمکانکردند.گروههمچنانبهاجراهایبین‌المللیخودادامهمی‌دادواز۱۹۷۶تا۱۹۸۴(از۱۵تا۲۴سالگیمایکل)ششآلبوماستودیوییدیگرمنتشرکرد.درهمینمدت،مایکلترانه‌سرایاصلیگروهجکسونزبود.Cantional,oderGesangbuchAugsburgischerKonfessionin1627.ohannSebastianBachcomposedafour-partsetting,BWV285,whichiswithouttext.twaspublishedasNo.196inthecollectionofchoralesbyJohannPhilippKirnbergerundCarlPhilippEmanufread');
Nicholas answered 11/8, 2018 at 12:28 Comment(0)
Z
0

If you need a program without in-built function, can try this, it will give you an array of each letter with total count.

<?php

$string = "cdcdcdcdeeeef";
$result = [];

for ($i = 0; $i < strlen($string); $i++) {
    if (isset($result[$string[$i]])) {
        $result[$string[$i]] += 1;
    } else {
        $result[$string[$i]] = 1;
    }
 }
 print_r($result);      
Zeus answered 11/4 at 18:46 Comment(0)
B
-1

you can do it by following way as well:

$str = 'aabbbccccdddeeedfff';
$arr = str_split($str);
$result = array_count_values($arr);
$string = http_build_query($result,'','');
echo str_replace('=','',$string);

Bolen answered 16/9, 2019 at 9:24 Comment(1)
This answer makes no attempt to educate researchers.Mucronate

© 2022 - 2024 — McMap. All rights reserved.