Utilizing the Short-hand if() within a PHP String
Until recently, one thing has eluded me when it comes to the Ternary Operator [aka the short-hand if()]. It's easy to assign the resulting value to a variable or to display it on the screen, but how is the short-hand if() used in conjunction with the concatenation character? In other words, how is it used in the middle of a PHP string?
Background
Last week's post "Getting Your Projects Done Faster by Writing Less Code with the Short-hand if()" describes how to assign the resulting value to a variable, for example:
<?php
$checkbox_value1 = ($_POST['checkbox_value1']) ? 1 : 0;
?>
To display the value to the screen, just replace the assignment part with "echo":
<?php
echo ($_POST['checkbox_value1']) ? 1 : 0;
?>
Example
What if we want to display the value in the middle of a sentence? For example, let's say we're looking to display the visitor's name (if known) within a set of instructions. We could write multiple echo statements:
<?php
echo 'Welcome ';
echo ($visitor_name != '') ? $visitor_name : 'Guest';
echo ', please use the options above to find what you are looking for.';
?>
Solution
However, it would be nice if we could avoid typing "echo" over and over again. Under normal circumstances, we would replace the extra echoes and semi-colons with the concatenation character, but that doesn't quite work in this case. We also need to surround the short-hand if() with parenthesis.
<?php
echo 'Welcome ' . (($visitor_name != '') ? $visitor_name : 'Guest') . ', please use the options above to find what you are looking for.';
?>
0 Comments
There are currently no comments.
Leave a Comment