patternphpMinor
Print out a student's former name if it is not empty
Viewed 0 times
studentformeremptyprintnamenotout
Problem
(!empty($student->former_name) ? print $student->former_name : '');I only want to print out the former name if it is not empty, nothing else.
I imagine I do not need the else part of it, but I do not know how to do it like that without the else.
I want to shorthand this:
if(!empty($student->former_name))
print $student->former_name;Solution
Why not just
If its empty, it will be an empty string and thus the same thing. There is no way to remove the else from a ternary statement. The only other way to write that would be like so:
Edit: Actually, I sort of lied above, you could remove the empty check altogether.
And of course, if your PHP version is >= 5.3, then you could use short ternary, assuming that your statement returns the same value that your if section should return.
echo $student->former_nameIf its empty, it will be an empty string and thus the same thing. There is no way to remove the else from a ternary statement. The only other way to write that would be like so:
echo empty( $student->former_name ) ? '' : $student_former_name;Edit: Actually, I sort of lied above, you could remove the empty check altogether.
echo $student->former_name ? $student->former_name : '';And of course, if your PHP version is >= 5.3, then you could use short ternary, assuming that your statement returns the same value that your if section should return.
echo $student->former_name ?: '';Code Snippets
echo $student->former_nameecho empty( $student->former_name ) ? '' : $student_former_name;echo $student->former_name ? $student->former_name : '';echo $student->former_name ?: '';Context
StackExchange Code Review Q#15324, answer score: 7
Revisions (0)
No revisions yet.