Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
(!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;
share|improve this question

2 Answers

up vote 4 down vote accepted

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 ?: '';
share|improve this answer
I needed to append the former name within parentheses, I did not include them originally for simplicity. Your second option looks better, thanks. – Brad Sep 4 '12 at 15:53
@Brad: Edited comment, for 5.3 used to having to do things for 5.2. – mseancole Sep 4 '12 at 16:41

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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