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

Pymnpeere

New Member
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-generated content, and so I need to display the author of this content in many different locations of the site (comments, posts, etc.). In the user's profile, he is able to (optionally) fill out his "first name", his "last name", and a "display name". To display the author, I wrote a helper method that looks through a provided array of these fields and returns the most appropriate name for the user, in this order of preference:[*]If the user filled out \[code\]display_name\[/code\], this will be displayed.[*]If the user filled out \[code\]first_name\[/code\] and \[code\]last_name\[/code\], but no \[code\]display_name\[/code\], it will display both names[*]If the user only filled out \[code\]first_name\[/code\], it will display \[code\]first_name\[/code\].[*]If the user only filled out \[code\]last_name\[/code\], it will display \[code\]last_name\[/code\].[*]If all else fails, a user id will be displayed i.e. \[code\]user123\[/code\][*]If none of the array keys are present, or the parameter is NULL, the name will display as \[code\]NULL\[/code\] The method works great, but it's ugly. There must be a way to beautify this with an alternative to nested if/else statements.\[code\]public function nameify($names = NULL) { $name = ''; if (!empty($names)) { if (!empty($names['display_name'])) { $name = $names['display_name']; } elseif (!empty($names['first_name'])) { $name = $names['first_name']; if (!empty($names['last_name'])) { $name .= ' ' . $names['last_name']; } } elseif (!empty($names['last_name'])) { $name = $names['last_name']; } if (empty($name) && !empty($names['id'])) { $name = 'user' . $names['id']; } else { $name = 'NULL'; } } else { $name = 'NULL'; } return $name;}\[/code\]
 
Back
Top