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
foreachloop
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
- Added a tracking array:
$processedCharskeeps 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. - 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. - Cleaner variable names: Renamed vague variables like
$jto$lengthand$valto$countto 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
相关产品推荐
相关产品推荐

