What is a more elegant solution to these nested if/elseif statements?

后端 未结 9 1838
野趣味
野趣味 2021-01-12 17:09

I\'m building a website that contains users with user profiles. Many of the fields in the profile are optional.

There is an opportunity for a lot of user-generate

9条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 17:52

    I would propose this:

    public function nameify($names = null) {
        if(empty($names))
            return null;
    
        if(!empty($names['display_name']))
            return $names['display_name'];
    
        if(!empty($names['first_name'])) {
            $name = $names['first_name'];
            if (!empty($names['last_name'])) {
                $name .= ' ' . $names['last_name'];
            }
            return $name;
        }
    
        if(!empty($names['id]))
            return 'user' . $names['id'];
    
        return null;
    }
    

提交回复
热议问题