这可以写得更好吗? PHP代码

问题描述:

我正在尝试生成最终字符串以显示基于某些条件的用户。这可以写得更好吗? PHP代码

$flag=0; 
$var='Please '; 
if($user->is_details_updated == 'N' && $user->needs_to_update_details == "Y") 
{ 
    $var='update your profile details'; 
    $flag=1; 
} 
if ($flag ==1) 
{ 
    $var=' and '; 
} 
if($user->is_pass_changed == 'N' && $user->needs_to_update_password == "Y") 
{ 
    $var.='change password'; 
} 

所以,如果三个if回报true然后最终$var看起来是这样的:

请更新您的个人资料详细信息和更改密码

这可怎么写比较好?

+0

你可以在[Code Review](http://codereview.stackexchange.com/)上发表 - 另一个StackExchange页面,这个问题比这里更适合。 – Xaerxess 2011-06-03 11:42:08

您可以邮件添加到阵列,然后用and

$var = arrray() 
if($user->is_details_updated == 'N' && $user->needs_to_update_details == "Y") 
{ 
    $var[] ='update your profile details'; 

} 

if($user->is_pass_changed == 'N' && $user->needs_to_update_password == "Y") 
{ 
    $var[]='change password'; 
} 

echo join(" and ", $var); 
+0

该死的,只是打到它...... +1 :)。 – Matt 2011-06-03 11:41:06

+1

@ skowron-line不要使用“U”,请在Stack Overflow上使用“你”。 “聊天说话”在此处被明确禁止。 – meagar 2012-06-11 20:59:31

+0

@meagar抱歉,这个im用来写这样的。但会改变它 – 2012-06-11 22:10:22

如何加入他们:

$sayings = array(); 

if($user->is_details_updated == 'N' && $user->needs_to_update_details == "Y") { 
    $sayings[] = 'update your profile details'; 
} 

if($user->is_pass_changed == 'N' && $user->needs_to_update_password == "Y") { 
    $sayings[] = 'change password'; 
} 

$var = 'Please ' . implode(' and ', $sayings); 

另一项建议是(如果可能的话),以重构$user->is_details_updated$user->needs_to_update_details$user->is_pass_changed$user->needs_to_update_password属性返回布尔值true/false值。这可能会在稍后节省一些调试头痛。