简体   繁体   中英

Store count of each letter in string in php

I am new to PHP Development. I want to be able to store each of the character count of a word in an array.

so if word is " test ".

I want something like

arr[t] = 2
arr[e] = 1
arr[s] = 1

In terms to ASCII I would actually want something like:

arr[116] = 2
arr[101] = 1
arr[115] = 1

Below is what I have tried:

 <?php
    $content = file_get_contents($argv[1]);
    $arr = explode(" ", $content);
    $countArr = array();
    for($x = 0; $x < strlen($arr[0]); $x++)
    {
        $countArr[$arr[0][$x]]++;    // taking first word and trying to store count of each letter
    }
    for($x = 0; $x < 256; $x++)
    {
        echo $countArr[$x];    // trying to print the count values  
    }
    ?>

It does not seem to work. In c++ I used to do something like this and it used to work. Am i missing something here. Please help.

You need to use str_split , array_count_values and ord for getting all the desire output. Simply array_count_values gives you the first desire output and if you want to use ascii value as array key then use ord .

$str = "test";
$arr = str_split($str);
$count_val = array_count_values($arr);

$res_ascii = array();
foreach($count_val as $k => $v){
    $res_ascii[ord($k)] = $v;
}

print_r($count_val); // Array ( [t] => 2 [e] => 1 [s] => 1 )
print_r($res_ascii); // Array ( [116] => 2 [101] => 1 [115] => 1 )

I am able to code the answer: PS: It might not be fool proof.

<?php
// Program to find the word in a sentence with maximum specific character count
// Example: "O Romeo, Romeo, wherefore art thou Romeo?”
// Solution: wherefore 
// Explanation: Because "e" came three times
$content = file_get_contents($argv[1]); // Reading content of file
$max = 0;
$arr = explode(" ", $content); // entire array of strings with file contents
for($x =0; $x<count($arr); $x++) // looping through entire array 
{
$array[$x] = str_split($arr[$x]); // converting each of the string into array
}
for($x = 0; $x < count($arr); $x++)
{
    $count = array_count_values($array[$x]);
    $curr_max = max($count);
    if($curr_max > $max)
    {
        $max = $curr_max;
        $word = $arr[$x];
    }
}
echo $word;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM