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

后端 未结 9 1922
野趣味
野趣味 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 18:06

    Using ternary conditions we can shorten and beautify the code:

    public function nameify($names = NULL) {
        $name = 'NULL';
    
        if (!empty($names)) {
    
            $name = ($names['display_name']) ? $names['display_name'] : trim($names['first_name']." ".$names['last_name']);
    
            if(!$name) $name = ($names['id'] > 0) ? 'user'.$names['id'] : 'NULL';
        }
    
        return $name;
    }
    

提交回复
热议问题