You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP字符串字符频次统计代码优化:查重并精简实现

Optimizing Your PHP Character Count Program

Hey, let's refine your code to cut down on redundant work and make it more efficient, exactly as you requested! Your original code gets the job done, but it wastes cycles re-counting characters we've already handled. Here's how to fix that:

Key Improvements We'll Make

  • Add a check to skip characters we've already counted
  • Output results immediately instead of storing them in an array first to skip the final foreach loop

Optimized Code

<?php
$myString = "palash";
$length = strlen($myString);
$processedChars = []; // Tracks characters we've already counted

for ($i = 0; $i < $length; $i++) {
    $currentChar = $myString[$i];
    
    // Skip if we've already processed this character
    if (in_array($currentChar, $processedChars)) {
        continue;
    }
    
    // Count occurrences of the current character
    $count = 0;
    for ($k = 0; $k < $length; $k++) {
        if ($myString[$k] === $currentChar) {
            $count++;
        }
    }
    
    // Mark this character as processed to avoid re-counting
    $processedChars[] = $currentChar;
    
    // Output the result right away
    echo "$currentChar-$count ";
}
?>

Breakdown of Changes

  1. Added a tracking array: $processedChars keeps track of every character we've already counted. Before starting the inner count loop, we check if the current character is in this array—if yes, we skip to the next iteration immediately.
  2. Removed the final foreach: Instead of storing all counts in an array and looping through it later, we print each result as soon as we calculate it. This saves memory and simplifies the code.
  3. Cleaner variable names: Renamed vague variables like $j to $length and $val to $count to make the code easier to read.

Bonus: Even Shorter with PHP Built-in Function

If you want to go even more concise, PHP has a built-in function count_chars that handles character counting efficiently. Here's how to use it:

<?php
$myString = "palash";
// Get an array of character => count pairs (only for characters present in the string)
$charCounts = count_chars($myString, 3);
foreach ($charCounts as $char => $count) {
    echo "$char-$count ";
}
?>

This function is optimized at the PHP core level, so it's faster than manual loops for longer strings.

内容的提问来源于stack exchange,提问作者Rimon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:56:49