TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Don't check emptyness before loops

2 pointsby gnoackover 4 years ago

1 comment

Minor49erover 4 years ago
I agree with the author, though the advice might be harder to follow in certain weakly-typed languages. For example, in PHP, developers have often used a false or null value to represent emptiness. An empty() check will return true on these values. However, booleans and nulls are not iterable. So if you tried to do something like this:<p><pre><code> $stuff = null; foreach ($stuff as $item) { var_dump($item); } </code></pre> you would be greeted with an &quot;Invalid argument supplied for foreach()&quot; warning. So it&#x27;s common to see the extra code that the author mentions:<p><pre><code> $stuff = null; if (! empty($stuff)) { foreach ($stuff as $item) { var_dump($item); } } </code></pre> You can get around this by using a null coalesce (??) or a ternary shorthand (?:) for null or boolean values respectively. This shows the former which gets closer to what the author describes for this situation, though it may sacrifice some readability under certain situations:<p><pre><code> $stuff = null; foreach ($stuff ?? [] as $item) { var_dump($item); }</code></pre>
评论 #24701059 未加载