简体   繁体   中英

Counting the number of letters in a word by PHP

I want to create an array which has two columns. The output should contain only the existing letters in the word with their amounts.

The wanted output of the following code

a 3
s 2
p 1

What is wrong in the following PHP code?

<?php

$alpha = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','z','y');

$word = "saapas";

for ( $i = 0; $i < count($word); $i++ ) {
        echo $word[$i] . "\n";

        $table[$word[$i]][]++;           // Problem here
}


// array_unique, array_combine and some method which can sort arrays by alphabets can be useful 

PHP has extensive array functions that do much of the heavy lifting for this:

$keys = range('a', 'z');
$values = array_fill(0, 26, 0);
$freq = array_combine($keys, $values);
$word = "saapas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
  $letter = strtolower($word[$i]);
  if (array_key_exists($letter, $freq)) {
    $freq[$letter]++;
  }
}
print_r($freq);

Output:

Array
(
    [a] => 3
    [b] => 0
    [c] => 0
    [d] => 0
    [e] => 0
    [f] => 0
    [g] => 0
    [h] => 0
    [i] => 0
    [j] => 0
    [k] => 0
    [l] => 0
    [m] => 0
    [n] => 0
    [o] => 0
    [p] => 1
    [q] => 0
    [r] => 0
    [s] => 2
    [t] => 0
    [u] => 0
    [v] => 0
    [w] => 0
    [x] => 0
    [y] => 0
    [z] => 0
)

If you want to distinguish between uppercase and lowercase try:

$keys = array_merge(range('a', 'z'), range('A', 'Z'));
$values = array_fill(0, 52, 0);
$freq = array_combine($keys, $values);
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
  $letter = $word[$i];
  if (array_key_exists($letter, $freq)) {
    $freq[$letter]++;
  }
}
print_r($freq);

Or to count any characters:

$freq = array();
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
  $letter = $word[$i];
  if (array_key_exists($letter, $freq)) {
    $freq[$letter]++;
  } else {
    $freq[$letter] = 1;
  }
}
print_r($freq);

This works using your input characters array, but do you really want to build a static array for this task?

$table = array();
$count = strlen($word);
for ( $i = 0; $i < $count; $i++ ) {
    $letter = $word[$i];
    if ( !isset($table[$letter]) )
    {
        $table[$letter] = 0;
    }
    ++$table[$letter];
}

Here's a method of doing the same thing, but utilizing PHP's native functions:

$ascii = count_chars($word, 1);
$keys = array_keys($ascii);
$chars = array_map('chr', $keys);
$charCount = array_values($ascii);
$table = array_combine($chars, $charCount);

Why complicate?

$string = 'the grey fox jumps over the lazy dog';
$words = explode(' ', $string);

foreach ($words as $key => $value)
{
    $words[$key] = count_chars($value, 1);
}

echo '<pre>';
print_r($words);
echo '</pre>';
    for ( $i = 0; $i < $alpha.length; $i++ ) {

        $count = 0;
        for($a = 0; $a < count($word); $a++)
        {
            if($word[$a] == $array[$i]
                $count++;
        }
        if($count > 0)
             echo $array[$i] . " " . $count . "\n";

    }

So we use 2 for loops. A little inefficient that what your trying to do. One to check for each character of the alphabet. The second loop is to loop through the string and count the matches against the alphabet the first loop is on.

Edit: Or you could add a zero to the line below and remove the echo from the loop. Which still requires another loop to display this table.

$table[$word[$i]][0]++;

try this out.it is a single iteration method and faster and simple!

<?php

$word = "saapas";
$result;
for ( $i = 0; $i < strlen($word); $i++ ) {
        echo $word[$i] . "\n";
        $result[$word[$i]]++; //make use of associative arrays to store the count for each alphabet.
}
foreach($result as $key => $value)//print each element inside the result array
{
print $key . " = " . $value . "<br />";
}
?>

count() doesn't quite work that way, you have to explicitly convert to an array if you want to use the count function. As for the $table array, you have an extra dimension (the []).

The following code should work (it is not optimal but should get you pointed in the right direction.)

$word = str_split("saapas");

for ( $i = 0; $i < count($word); $i++ ) {
    $table[$word[$i]]++;
}

foreach ($table as $key => $value) {
    print "$key $value\n";
}

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