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
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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.