TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Don't check emptyness before loops

2 点作者 gnoack超过 4 年前

1 comment

Minor49er超过 4 年前
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 未加载