如何整理多个 if 条件以提高可读性?
如何整理多个 if 条件以提高可读性?
例如,
if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user' )
当处于这种情况的物品变长时,这会让我感到困惑。
它在下面的这种情况下使用 - foreach()
,
$editable_fields = array(
'pg_id',
'pg_url',
'pg_title',
'pg_subtitle',
'pg_description',
'pg_introduction',
'pg_content_1',
'pg_content_2',
'pg_content_3',
'pg_content_4',
'pg_backdate',
'pg_highlight',
'pg_hide',
'pg_cat_id',
'ps_cat_id',
'parent_id',
'tmp_id',
'usr_id'
);
$sql_pattern = array();
foreach( $editable_fields as $key )
{
if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user' ) $sql_pattern[] = "$key = ?";
}
我正在考虑使用 switch 但我想我错了!
How can I tidy multiple if condition for readability?
For instance,
if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user' )
This confuses me when the items in that condition grow longer.
It was used in this kind of situation below - foreach()
,
$editable_fields = array(
'pg_id',
'pg_url',
'pg_title',
'pg_subtitle',
'pg_description',
'pg_introduction',
'pg_content_1',
'pg_content_2',
'pg_content_3',
'pg_content_4',
'pg_backdate',
'pg_highlight',
'pg_hide',
'pg_cat_id',
'ps_cat_id',
'parent_id',
'tmp_id',
'usr_id'
);
$sql_pattern = array();
foreach( $editable_fields as $key )
{
if( $key != 'pg_id' && $key != 'pg_tag' && $key != 'pg_user' ) $sql_pattern[] = "$key = ?";
}
I was thinking using switch but I think I was wrong!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
in_array
:You could use
in_array
:一种可能的解决方案是将每个条件放在自己的行上:
我发现这为我澄清了这些类型的复合条件。
One possible solution could be to put each condition on it's own line:
I find this clarifies these types of compound conditions for me.
因此,使用换行符:
使其更具可读性。
switch
语句仅用于测试一种条件。就像您要检查号码一样。So, use line-breaks:
Makes it more readable.
A
switch
-statement is meant to test only for one condition. Like if you would check for a number.您可以将其展开:
...或使用 switch 语句
You can either spread it out:
... or use a switch statement
重构为具有描述其用途的名称的函数:
Refactor into a function with a name that describes its purpose: