Conditionally execute PHP code with an if statement

Every programming language has the concept of conditional statements. If this, then that.

PHP is definitely not any different. To write a condition, we’ll of course need to be within a PHP tag. We can write everything within one code block like this, or use two or more inline PHP statements. For now let’s use the block method, as it is more common to write code like this in PHP programs.

<?php
$title = 'My Blog';
$numPosts = 10;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php

?>

Let’s type if, and afterwards comes an open & closed parenthesis. Within these comes a condition. We can write a condition right inline like this, and this is usually how most write if statements.

<?php
$title = 'My Blog';
$numPosts = 10;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php
if ($numPosts > 0)
?>

Note how we have a $hasPosts variable already though is already assigned the result of this condition. If we didn’t already have this variable, it would be a good idea to write our condition and store the result within one. Not only does this make our code easier to read, but it also makes our code read like human language.

<?php
$title = 'My Blog';
$numPosts = 10;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php
if ($hasPosts)
?>

“if has posts” is a lot easier to understand than “if num posts greater than 0”. The variable name also provides meaning to the condition, “self-documenting” the code along the way, which helps us avoid bugs in the future.

Next comes an open and closed bracket. Within the bracket is where we will execute our code if the condition is true. In this case, let’s just echo out “Posts exist.”

<?php
$title = 'My Blog';
$numPosts = 10;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php
if ($hasPosts) {
    echo 'Posts exist.';
}
?>

This is currently a valid if statement. If we refresh the page, we will see that posts exist.

We can also supply an “else” condition, which will execute this block of code whenever the checked condition is false. We can do this by typing else after our closing bracket tag, then another open & close bracket.

If we change our $numPosts value to 0, save, and refresh the page, we will see that it triggers this else condition, because $hasPosts will evaluate to false.

<?php
$title = 'My Blog';
$numPosts = 0;
$hasPosts = $numPosts > 0;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php
if ($hasPosts) {
    echo 'Posts exist.';
} else {
    echo 'There are no posts.';
}
?>


Complete and Continue