(!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:

 print $student->former_name;

3 Answers 3


Why not just

echo $student->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->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 ?: '';
  • \$\begingroup\$ I needed to append the former name within parentheses, I did not include them originally for simplicity. Your second option looks better, thanks. \$\endgroup\$
    – Brad
    Commented Sep 4, 2012 at 15:53
  • \$\begingroup\$ @Brad: Edited comment, for 5.3 used to having to do things for 5.2. \$\endgroup\$
    – mseancole
    Commented Sep 4, 2012 at 16:41

Please find few alternatives below:

print @$a->b; // @ will ignore the PHP notices
$a->b && print $a->b; // This version could generate some PHP notices.
!empty($a->b) && print $a->b;
echo !empty($a->b) ? $a->b : NULL;
print !empty($a->b) ? $a->b : NULL;
!empty($a->b) ? print $a->b : NULL;
if (!empty($a->b)): print $a->b; endif;
if (!empty($a->b)) print $a->b;

Note: Instead of NULL you still can use ''. $a->b in your case it's the same as $student->former_name.


The simplest way to do this would be:-

if(!empty($student->former_name)) print $student->former_name;

The way you are using the ternary statement there is inappropriate, which is illustrated by your difficulty in using it.

Your ternary statement is harder to read, is no shorter, so my advice would be to go with the single line if statement.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.