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

后端 未结 9 1930
野趣味
野趣味 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:56

    I'm not sure that my version would be simplier, but here it is:

    public function nameify($names = null) {
        $result = array();
    
        if( !empty($names['display_name']) ) {
            array_push($result,$names['display_name']);
        } else {
            if( !empty($names['first_name']) ) {
                array_push($result, $names['first_name']);
            }
            if( !empty($names['last_name']) ) {
                array_push($result, $names['last_name']);
            }
        }
    
        if( empty($result) && !empty($names['id']) ) {
            array_push($result, 'user'.$names['id']);
        }
    
        return (empty($result) ? 'NULL' : implode(' ', $result));
    }
    

提交回复
热议问题