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
display_name
, this will be displayed. - If the user filled out
first_name
andlast_name
, but nodisplay_name
, it will display both names - If the user only filled out
first_name
, it will displayfirst_name
. - If the user only filled out
last_name
, it will displaylast_name
. - If all else fails, a user id will be displayed i.e.
user123
- If none of the array keys are present, or the parameter is NULL, the name will display as
NULL
The method works great, but it's ugly. There must be a way to beautify this with an alternative to nested if/else statements.
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;
}