Print out a student's former name if it is not empty (!empty($student-&gt;former_name) ? print $student-&gt;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-&gt;former_name))
 print $student-&gt;former_name;
Why not just

echo $student-&gt;former_name


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:

echo empty( $student-&gt;former_name ) ? '' : $student_former_name;


Edit: Actually, I sort of lied above, you could remove the empty check altogether.

echo $student-&gt;former_name ? $student-&gt;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-&gt;former_name ?: '';