Jump to content

Strange behavior with ternary operator


johnmerlino

Recommended Posts

Hey all,

when job_title property is equal to null, I want this to happen:

 

Welcome to the blog of John Merlino.

 

If it is not null then:

 

Welcome to the blog of John Merlino, a web designer. //where web designer refers to the value stored in job_title

 

So I come up with this:

 

echo "Welcome to the blog of " . $blogger->first_name . ' ' . $blogger->last_name  . (!is_null($blogger->job_title)) ? ', ' . $blogger->job_title . '.' : '.';

 

But when job_title is null, all the page renders is this:

, .

 

That's right. Just a comma, then a space, and then a period.

 

What am I missing here?

 

Thanks for response.

 

Link to comment
https://forums.phpfreaks.com/topic/231866-strange-behavior-with-ternary-operator/
Share on other sites

Now this works fine:

 

	$str = "Welcome to the blog of " . $blogger->first_name . ' ' . $blogger->last_name;
	$str .= (!is_null($blogger->job_title)) ? ', ' . $blogger->job_title . '.' : '.';
	echo $str;

 

But why the need for string concatenation here? Why couldn't I stick ternary on the same line?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.