I am creating a website containing users with user profiles. Many fields in the profile are optional.
There is an opportunity for a large number of user content, so I need to display the author of this content in many different places on the site (comments, posts, etc.). In the user profile, he can (optionally) fill in his "first name", his "last name" and "display name".
To display the author, I wrote a helper method that looks at the provided array of these fields and returns the most suitable name for the user in this order of preference:
- If the user populated
display_name , this will be displayed. - If the user filled in
first_name and last_name but not display_name , it will display both names - If the user has filled in only
first_name , first_name will be displayed. - If the user fills only
last_name , it displays last_name . - If all else fails, the user ID will be displayed, i.e.
user123 - If none of the array keys is present or the parameter is NULL, the name will be displayed as
NULL
The method works fine, but it's ugly. There should be a way to decorate 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; }
string php user-input helper
Stephen
source share