johnmerlino Posted March 27, 2011 Share Posted March 27, 2011 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 More sharing options...
johnmerlino Posted March 27, 2011 Author Share Posted March 27, 2011 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 https://forums.phpfreaks.com/topic/231866-strange-behavior-with-ternary-operator/#findComment-1192888 Share on other sites More sharing options...
nethnet Posted March 27, 2011 Share Posted March 27, 2011 You could have put it on the same line if you enclosed the entire ternary operation inside parentheses. Link to comment https://forums.phpfreaks.com/topic/231866-strange-behavior-with-ternary-operator/#findComment-1192889 Share on other sites More sharing options...
johnmerlino Posted March 27, 2011 Author Share Posted March 27, 2011 thanks for response. Link to comment https://forums.phpfreaks.com/topic/231866-strange-behavior-with-ternary-operator/#findComment-1192899 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.