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
It is not much, but because $name it is at least NULL:
public function nameify($names = NULL) {
$name = 'NULL';
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 ($name=='NULL' && !empty($names['id'])) {
$name = 'user' . $names['id'];
}
}
return $name;
}
Somewhat less readable, but effective):
list($idx,$name) = array_shift(array_filter(array(
$names['display_name'],
implode(' ',array_filter(array($names['first_name'],$names['last_name']))),
'user'.$names['id'];
)));
A State machine works very nicely for involved logic like that. It's very simple to implement as well (using a switch statement).
I would propose this:
public function nameify($names = null) { if(empty($names)) return null; if(!empty($names['display_name'])) return $names['display_name']; if(!empty($names['first_name'])) { $name = $names['first_name']; if (!empty($names['last_name'])) { $name .= ' ' . $names['last_name']; } return $name; } if(!empty($names['id])) return 'user' . $names['id']; return null; }
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));
}
I'd go with:
if( empty($names['display_name']) ) {
$name = $names['first_name'] . ' ' $names['last_name'];
else
$name = $names['display_name'];
$name = trim($name);
if( empty($name) )
$name = 'user'.$names['id'];
if( empty($name) )
$name = 'NULL';
This would be the 'core logic'... there will need to be other checks like $names != NULL
or something..