如何精简代码?PHP7中这段isset判断代码能否更简短?
Hey there! Great questions—let's tackle them one by one, keeping things practical and readable (since concise code doesn't have to mean confusing code!).
Trimming down code while maintaining clarity is a balance, but here are my go-to strategies:
- Lean into language-specific shorthands: Modern languages like PHP7+ have built-in shortcuts to cut redundancy. For example, use null coalescing operators (
??) instead of verboseisset()checks, or arrow functions for tiny callbacks. - Simplify conditionals: Replace straightforward
if-elseblocks with ternary operators, or chain null coalescing/ternary checks for multi-step logic. - Use built-in functions: Don’t reinvent the wheel—languages ship with optimized functions for common tasks (like
count()for arrays in PHP instead of writing a custom loop). - Cut redundant checks: If you’ve already verified a variable’s existence or value later in your code, skip repeating the check earlier.
- Combine safe operations: Merge multiple small steps into one line only if it stays easy to parse (readability always wins over brevity!).
First, let’s look at your original code:
if(isset($content[$i]['count'])) $content[$i]['count'] = 1; else $content[$i]['count'] += $content[$i]['count'];
⚠️ Quick note: The else branch here will throw an Undefined index warning if $content[$i]['count'] doesn’t exist—you can’t perform addition on an undefined variable. This is likely a typo, so I’ll cover both the corrected logical intent and a fix for the original structure.
Scenario 1: Corrected common intent (initialize or reset to 1)
If your goal is to set $content[$i]['count'] to 1—whether the key exists or not—you can skip the check entirely:
$content[$i]['count'] = 1;
If you meant "set to 1 if it exists, else initialize to 1" (which makes the original if-else redundant), use PHP7.4+'s null coalescing assignment operator for a clean one-liner:
$content[$i]['count'] ??= 1;
Or if your actual goal was "increment by 1 if it exists, else set to 1" (a super common pattern):
$content[$i]['count'] = ($content[$i]['count'] ?? 0) + 1;
Scenario 2: Fixing the original (error-free) logic
If you truly want to set the value to 1 when it exists, and double it when it doesn’t (first ensuring the key exists), here’s a concise, error-safe version:
$content[$i]['count'] = isset($content[$i]['count']) ? 1 : (($content[$i]['count'] = 0) * 2);
Or for a shorter (still readable) take using short-circuit evaluation:
isset($content[$i]['count']) ? ($content[$i]['count'] = 1) : ($content[$i]['count'] = 0);
内容的提问来源于stack exchange,提问作者Areza

