Refactor a PHP if else statement into a ternary

Because checking a truthy result is so common, PHP supplies a simplified if/else shorthand syntax called a ternary. This is useful when you want to execute a very simple statement based on the result of a condition.

Rather than if & else, we use a ? and :.

Let’s remove the “exactly 3 posts” logic, since we won’t be using that anymore.

We will now refactor this hasPosts logic into a ternary. Since we are echo’ing out two lines, we can write our echo keyword first, followed by the condition.

Next comes a question mark, which is the equivalent of the open & close brackets of an if statement. Then we will return what we want to execute when this condition is true. So, this will be the “Posts exist.” string.

Followed immediately after this is a colon, representing the “else” part of the condition. This follows the same format as the question mark, so the result of executing the else condition. This will output “There are no posts.”.

<?php
$title = 'My Blog';
$numPosts = 10;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php echo $hasPosts ? 'Posts exist' : 'There are no posts.' ?>

When we fresh the page, we’ll notice that this works exactly the same as our previous code. When we change $numPosts to 0 and refresh the page, our “There are no posts” message will be outputted.

The vigilant watchers will have noticed this php tag is followed by the echo keyword, and realize that this can also be refactored to use the short echo tag format.

This can give us the highest terseness, or most concise code possible for this block of code. This represents an echo, we are checking if $hasPosts is true, and if it is, we are outputting “Posts exists.”, otherwise it outputs the “There are no posts.” message.

<?php
$title = 'My Blog';
$numPosts = 10;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?= $hasPosts ? 'Posts exist' : 'There are no posts.' ?>

I greatly prefer ternaries when used in this format of short echo & conditions that are assigned to well-named variables, as they are just so simple & easy to read once you get used to the format.

Just keep in mind that you only really ever want to use a ternary when you are dealing with boolean logic, that is mainly just a single true or false condition. I also use this method a lot in backend PHP code when evaluating & returning values from boolean checks.

Whenever conditions get more complex or seem hard to follow, you’ll want to use the longer if/else format as it will be easier to understand for more complex conditional statements.

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock