开发者

How better this can be written? PHP code

I am trying to generate final string to show users based on some conditions.

$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_cha开发者_如何学Pythonnged == 'N' && $user->needs_to_update_password == "Y")
{   
    $var.='change password';
}

So, If all three if return true then final $var looks like this:

Please update your profile details and change password

How this can be written better?


You can add messages to array and then join them with 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);


How about:

$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);


Another suggestion would be (if possible) to refactor the $user->is_details_updated, $user->needs_to_update_details, $user->is_pass_changed, $user->needs_to_update_password properties to return boolean true/false values. This might save some debugging headaches later on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜